blob: bba24158c869e04674e4664fe91bb222df9cd5c5 [file] [log] [blame]
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001****************************
2 What's New In Python 3.3
3****************************
4
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00005:Release: |release|
6:Date: |today|
7
Éric Araujob07b97f2011-10-05 01:03:34 +02008.. Rules for maintenance:
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00009
10 * Anyone can add text to this document. Do not spend very much time
11 on the wording of your changes, because your text will probably
12 get rewritten to some degree.
13
14 * The maintainer will go through Misc/NEWS periodically and add
15 changes; it's therefore more important to add your changes to
16 Misc/NEWS than to this file.
17
18 * This is not a complete list of every single change; completeness
19 is the purpose of Misc/NEWS. Some changes I consider too small
20 or esoteric to include. If such a change is added to the text,
21 I'll just remove it. (This is another reason you shouldn't spend
22 too much time on writing your addition.)
23
24 * If you want to draw your new text to the attention of the
25 maintainer, add 'XXX' to the beginning of the paragraph or
26 section.
27
28 * It's OK to just add a fragmentary note about a change. For
29 example: "XXX Describe the transmogrify() function added to the
30 socket module." The maintainer will research the change and
31 write the necessary text.
32
33 * You can comment out your additions if you like, but it's not
34 necessary (especially when a final release is some months away).
35
36 * Credit the author of a patch or bugfix. Just the name is
37 sufficient; the e-mail address isn't necessary.
38
39 * It's helpful to add the bug/patch number as a comment:
40
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000041 XXX Describe the transmogrify() function added to the socket
42 module.
Éric Araujob07b97f2011-10-05 01:03:34 +020043 (Contributed by P.Y. Developer in :issue:`12345`.)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000044
Éric Araujob07b97f2011-10-05 01:03:34 +020045 This saves the maintainer the effort of going through the Mercurial log
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000046 when researching a change.
47
48This article explains the new features in Python 3.3, compared to 3.2.
R David Murrayf23e2b62012-09-29 19:41:26 -040049Python 3.3 was released on September 29, 2012. For full details,
50see the :source:`Misc/NEWS` file.
51
52.. seealso::
53
Nick Coghlancfb18182012-09-30 12:08:13 +053054 :pep:`398` - Python 3.3 Release Schedule
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000055
Nick Coghlanb47b5392012-05-26 01:31:25 +100056
Antoine Pitrouc907de92012-08-21 00:53:06 +020057Summary -- Release highlights
58=============================
Victor Stinner636130e2012-08-05 16:37:12 +020059
Antoine Pitrouc907de92012-08-21 00:53:06 +020060.. This section singles out the most important changes in Python 3.3.
61 Brevity is key.
Victor Stinner636130e2012-08-05 16:37:12 +020062
Antoine Pitrouc907de92012-08-21 00:53:06 +020063New syntax features:
Victor Stinner636130e2012-08-05 16:37:12 +020064
Antoine Pitrouc907de92012-08-21 00:53:06 +020065* New ``yield from`` expression for :ref:`generator delegation <pep-380>`.
66* The ``u'unicode'`` syntax is accepted again for :class:`str` objects.
Victor Stinner636130e2012-08-05 16:37:12 +020067
Antoine Pitrouc907de92012-08-21 00:53:06 +020068New library modules:
69
70* :mod:`faulthandler` (helps debugging low-level crashes)
71* :mod:`ipaddress` (high-level objects representing IP addresses and masks)
72* :mod:`lzma` (compress data using the XZ / LZMA algorithm)
Victor Stinner1da769a2012-09-18 22:40:03 +020073* :mod:`unittest.mock` (replace parts of your system under test with mock objects)
Antoine Pitrouc907de92012-08-21 00:53:06 +020074* :mod:`venv` (Python :ref:`virtual environments <pep-405>`, as in the
75 popular ``virtualenv`` package)
76
77New built-in features:
78
79* Reworked :ref:`I/O exception hierarchy <pep-3151>`.
80
81Implementation improvements:
82
83* Rewritten :ref:`import machinery <importlib>` based on :mod:`importlib`.
84* More compact :ref:`unicode strings <pep-393>`.
85* More compact :ref:`attribute dictionaries <pep-412>`.
86
R David Murrayf23e2b62012-09-29 19:41:26 -040087Significantly Improved Library Modules:
88
89* C Accelerator for the :ref:`decimal <new-decimal>` module.
90* Better unicode handling in the :ref:`email <new-email>` module
91 (:term:`provisional <provisional package>`).
92
Antoine Pitrouc907de92012-08-21 00:53:06 +020093Security improvements:
94
95* Hash randomization is switched on by default.
96
97Please read on for a comprehensive list of user-facing changes.
98
99
100.. _pep-405:
Victor Stinner636130e2012-08-05 16:37:12 +0200101
Éric Araujo859aad62012-06-24 00:07:41 -0400102PEP 405: Virtual Environments
103=============================
Nick Coghlanb47b5392012-05-26 01:31:25 +1000104
Antoine Pitroua5e57972012-08-21 01:08:17 +0200105Virtual environments help create separate Python setups while sharing a
106system-wide base install, for ease of maintenance. Virtual environments
107have their own set of private site packages (i.e. locally-installed
108libraries), and are optionally segregated from the system-wide site
109packages. Their concept and implementation are inspired by the popular
110``virtualenv`` third-party package, but benefit from tighter integration
111with the interpreter core.
Éric Araujo859aad62012-06-24 00:07:41 -0400112
Antoine Pitroua5e57972012-08-21 01:08:17 +0200113This PEP adds the :mod:`venv` module for programmatic access, and the
114:ref:`pyvenv <scripts-pyvenv>` script for command-line access and
Ezio Melottiad626802012-10-16 21:50:33 +0300115administration. The Python interpreter checks for a ``pyvenv.cfg``,
Antoine Pitroua5e57972012-08-21 01:08:17 +0200116file whose existence signals the base of a virtual environment's directory
117tree.
Nick Coghlanb47b5392012-05-26 01:31:25 +1000118
R David Murrayf23e2b62012-09-29 19:41:26 -0400119.. seealso::
120
121 :pep:`405` - Python Virtual Environments
Ezio Melotti36e01df2012-10-20 16:26:18 +0300122 PEP written by Carl Meyer; implementation by Carl Meyer and Vinay Sajip
R David Murrayf23e2b62012-09-29 19:41:26 -0400123
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000124
Ezio Melotti8cd45bd2012-10-21 07:36:58 +0300125PEP 420: Implicit Namespace Packages
126====================================
Éric Araujo859aad62012-06-24 00:07:41 -0400127
128Native support for package directories that don't require ``__init__.py``
129marker files and can automatically span multiple path segments (inspired by
130various third party approaches to namespace packages, as described in
131:pep:`420`)
132
R David Murrayf23e2b62012-09-29 19:41:26 -0400133.. seealso::
134
Ezio Melotti8cd45bd2012-10-21 07:36:58 +0300135 :pep:`420` - Implicit Namespace Packages
R David Murrayf23e2b62012-09-29 19:41:26 -0400136 PEP written by Eric V. Smith; implementation by Eric V. Smith
137 and Barry Warsaw
138
Éric Araujo859aad62012-06-24 00:07:41 -0400139
140.. _pep-3118-update:
Nick Coghlan98e20702012-03-06 21:50:13 +1000141
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100142PEP 3118: New memoryview implementation and buffer protocol documentation
143=========================================================================
144
R David Murrayf23e2b62012-09-29 19:41:26 -0400145The implementation of :pep:`3118` has been significantly improved.
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100146
147The new memoryview implementation comprehensively fixes all ownership and
148lifetime issues of dynamically allocated fields in the Py_buffer struct
149that led to multiple crash reports. Additionally, several functions that
150crashed or returned incorrect results for non-contiguous or multi-dimensional
151input have been fixed.
152
153The memoryview object now has a PEP-3118 compliant getbufferproc()
154that checks the consumer's request type. Many new features have been
155added, most of them work in full generality for non-contiguous arrays
156and arrays with suboffsets.
157
158The documentation has been updated, clearly spelling out responsibilities
159for both exporters and consumers. Buffer request flags are grouped into
160basic and compound flags. The memory layout of non-contiguous and
161multi-dimensional NumPy-style arrays is explained.
162
163Features
164--------
165
166* All native single character format specifiers in struct module syntax
167 (optionally prefixed with '@') are now supported.
168
169* With some restrictions, the cast() method allows changing of format and
170 shape of C-contiguous arrays.
171
172* Multi-dimensional list representations are supported for any array type.
173
174* Multi-dimensional comparisons are supported for any array type.
175
Stefan Krah9e31d362012-09-08 15:35:01 +0200176* One-dimensional memoryviews of hashable (read-only) types with formats B,
177 b or c are now hashable. (Contributed by Antoine Pitrou in :issue:`13411`)
Nick Coghlan98e20702012-03-06 21:50:13 +1000178
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100179* Arbitrary slicing of any 1-D arrays type is supported. For example, it
180 is now possible to reverse a memoryview in O(1) by using a negative step.
181
182API changes
183-----------
184
185* The maximum number of dimensions is officially limited to 64.
186
187* The representation of empty shape, strides and suboffsets is now
188 an empty tuple instead of None.
189
190* Accessing a memoryview element with format 'B' (unsigned bytes)
191 now returns an integer (in accordance with the struct module syntax).
192 For returning a bytes object the view must be cast to 'c' first.
193
Nick Coghlan06e1ab02012-08-25 17:59:50 +1000194* memoryview comparisons now use the logical structure of the operands
195 and compare all array elements by value. All format strings in struct
196 module syntax are supported. Views with unrecognised format strings
197 are still permitted, but will always compare as unequal, regardless
198 of view contents.
199
Stefan Krah54c32032012-02-29 17:47:21 +0100200* For further changes see `Build and C API Changes`_ and `Porting C code`_ .
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100201
R David Murrayf23e2b62012-09-29 19:41:26 -0400202(Contributed by Stefan Krah in :issue:`10181`)
203
204.. seealso::
205
206 :pep:`3118` - Revising the Buffer Protocol
207
208
Antoine Pitrou037ffbf2011-10-24 00:25:41 +0200209.. _pep-393:
210
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300211PEP 393: Flexible String Representation
212=======================================
213
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200214The Unicode string type is changed to support multiple internal
215representations, depending on the character with the largest Unicode ordinal
216(1, 2, or 4 bytes) in the represented string. This allows a space-efficient
217representation in common cases, but gives access to full UCS-4 on all
218systems. For compatibility with existing APIs, several representations may
219exist in parallel; over time, this compatibility should be phased out.
Ezio Melotti397546a2011-09-29 08:34:36 +0300220
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200221On the Python side, there should be no downside to this change.
Ezio Melotti397546a2011-09-29 08:34:36 +0300222
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200223On the C API side, PEP 393 is fully backward compatible. The legacy API
224should remain available at least five years. Applications using the legacy
225API will not fully benefit of the memory reduction, or - worse - may use
226a bit more memory, because Python may have to maintain two versions of each
227string (in the legacy format and in the new efficient storage).
228
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100229Functionality
230-------------
231
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200232Changes introduced by :pep:`393` are the following:
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300233
Ezio Melotti397546a2011-09-29 08:34:36 +0300234* Python now always supports the full range of Unicode codepoints, including
235 non-BMP ones (i.e. from ``U+0000`` to ``U+10FFFF``). The distinction between
236 narrow and wide builds no longer exists and Python now behaves like a wide
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200237 build, even under Windows.
Ezio Melotti397546a2011-09-29 08:34:36 +0300238
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200239* With the death of narrow builds, the problems specific to narrow builds have
240 also been fixed, for example:
Ezio Melotti397546a2011-09-29 08:34:36 +0300241
242 * :func:`len` now always returns 1 for non-BMP characters,
243 so ``len('\U0010FFFF') == 1``;
244
245 * surrogate pairs are not recombined in string literals,
246 so ``'\uDBFF\uDFFF' != '\U0010FFFF'``;
247
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200248 * indexing or slicing non-BMP characters returns the expected value,
Ezio Melotti397546a2011-09-29 08:34:36 +0300249 so ``'\U0010FFFF'[0]`` now returns ``'\U0010FFFF'`` and not ``'\uDBFF'``;
250
Antoine Pitroud136aec2011-11-17 01:48:06 +0100251 * all other functions in the standard library now correctly handle
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200252 non-BMP codepoints.
Ezio Melotti397546a2011-09-29 08:34:36 +0300253
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300254* The value of :data:`sys.maxunicode` is now always ``1114111`` (``0x10FFFF``
255 in hexadecimal). The :c:func:`PyUnicode_GetMax` function still returns
256 either ``0xFFFF`` or ``0x10FFFF`` for backward compatibility, and it should
257 not be used with the new Unicode API (see :issue:`13054`).
258
Ezio Melotti397546a2011-09-29 08:34:36 +0300259* The :file:`./configure` flag ``--with-wide-unicode`` has been removed.
Victor Stinner7d637ab2011-09-29 02:56:16 +0200260
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100261Performance and resource usage
262------------------------------
263
264The storage of Unicode strings now depends on the highest codepoint in the string:
265
266* pure ASCII and Latin1 strings (``U+0000-U+00FF``) use 1 byte per codepoint;
267
268* BMP strings (``U+0000-U+FFFF``) use 2 bytes per codepoint;
269
270* non-BMP strings (``U+10000-U+10FFFF``) use 4 bytes per codepoint.
271
Martin v. Löwisde157cc2012-03-06 08:42:17 +0100272The net effect is that for most applications, memory usage of string
273storage should decrease significantly - especially compared to former
274wide unicode builds - as, in many cases, strings will be pure ASCII
275even in international contexts (because many strings store non-human
276language data, such as XML fragments, HTTP headers, JSON-encoded data,
277etc.). We also hope that it will, for the same reasons, increase CPU
278cache efficiency on non-trivial applications. The memory usage of
279Python 3.3 is two to three times smaller than Python 3.2, and a little
280bit better than Python 2.7, on a Django benchmark (see the PEP for
281details).
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100282
R David Murrayf23e2b62012-09-29 19:41:26 -0400283.. seealso::
284
285 :pep:`393` - Flexible String Representation
286 PEP written by Martin von Löwis; implementation by Torsten Becker
287 and Martin von Löwis.
288
Éric Araujob07b97f2011-10-05 01:03:34 +0200289
Nick Coghlan349c8022012-09-30 13:00:43 +0530290.. _pep-397:
291
292PEP 397: Python Launcher for Windows
293====================================
294
295The Python 3.3 Windows installer now includes a ``py`` launcher application
296that can be used to launch Python applications in a version independent
297fashion.
298
299This launcher is invoked implicitly when double-clicking ``*.py`` files.
300If only a single Python version is installed on the system, that version
301will be used to run the file. If multiple versions are installed, the most
302recent version is used by default, but this can be overridden by including
303a Unix-style "shebang line" in the Python script.
304
305The launcher can also be used explicitly from the command line as the ``py``
306application. Running ``py`` follows the same version selection rules as
307implicitly launching scripts, but a more specific version can be selected
308by passing appropriate arguments (such as ``-3`` to request Python 3 when
309Python 2 is also installed, or ``-2.6`` to specifclly request an earlier
310Python version when a more recent version is installed).
311
312In addition to the launcher, the Windows installer now includes an
313option to add the newly installed Python to the system PATH (contributed
Brian Curtinf41d2022012-10-01 09:29:36 -0500314by Brian Curtin in :issue:`3561`).
Nick Coghlan349c8022012-09-30 13:00:43 +0530315
316.. seealso::
317
318 :pep:`397` - Python Launcher for Windows
319 PEP written by Mark Hammond and Martin v. Löwis; implementation by
320 Vinay Sajip.
321
322 Launcher documentation: :ref:`launcher`
323
324 Installer PATH modification: :ref:`windows-path-mod`
325
326
Antoine Pitrouc907de92012-08-21 00:53:06 +0200327.. _pep-3151:
328
Victor Stinnera1bf2982011-10-12 20:35:02 +0200329PEP 3151: Reworking the OS and IO exception hierarchy
330=====================================================
331
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200332The hierarchy of exceptions raised by operating system errors is now both
333simplified and finer-grained.
Victor Stinnera1bf2982011-10-12 20:35:02 +0200334
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200335You don't have to worry anymore about choosing the appropriate exception
336type between :exc:`OSError`, :exc:`IOError`, :exc:`EnvironmentError`,
337:exc:`WindowsError`, :exc:`mmap.error`, :exc:`socket.error` or
338:exc:`select.error`. All these exception types are now only one:
339:exc:`OSError`. The other names are kept as aliases for compatibility
340reasons.
Victor Stinnera1bf2982011-10-12 20:35:02 +0200341
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200342Also, it is now easier to catch a specific error condition. Instead of
343inspecting the ``errno`` attribute (or ``args[0]``) for a particular
344constant from the :mod:`errno` module, you can catch the adequate
345:exc:`OSError` subclass. The available subclasses are the following:
Victor Stinnera1bf2982011-10-12 20:35:02 +0200346
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200347* :exc:`BlockingIOError`
348* :exc:`ChildProcessError`
349* :exc:`ConnectionError`
350* :exc:`FileExistsError`
351* :exc:`FileNotFoundError`
352* :exc:`InterruptedError`
353* :exc:`IsADirectoryError`
354* :exc:`NotADirectoryError`
355* :exc:`PermissionError`
356* :exc:`ProcessLookupError`
357* :exc:`TimeoutError`
Victor Stinnera1bf2982011-10-12 20:35:02 +0200358
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200359And the :exc:`ConnectionError` itself has finer-grained subclasses:
Victor Stinnera1bf2982011-10-12 20:35:02 +0200360
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200361* :exc:`BrokenPipeError`
362* :exc:`ConnectionAbortedError`
363* :exc:`ConnectionRefusedError`
364* :exc:`ConnectionResetError`
Victor Stinnera1bf2982011-10-12 20:35:02 +0200365
366Thanks to the new exceptions, common usages of the :mod:`errno` can now be
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200367avoided. For example, the following code written for Python 3.2::
Victor Stinnera1bf2982011-10-12 20:35:02 +0200368
369 from errno import ENOENT, EACCES, EPERM
370
371 try:
372 with open("document.txt") as f:
373 content = f.read()
374 except IOError as err:
375 if err.errno == ENOENT:
376 print("document.txt file is missing")
377 elif err.errno in (EACCES, EPERM):
378 print("You are not allowed to read document.txt")
379 else:
380 raise
381
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200382can now be written without the :mod:`errno` import and without manual
383inspection of exception attributes::
Victor Stinnera1bf2982011-10-12 20:35:02 +0200384
385 try:
386 with open("document.txt") as f:
387 content = f.read()
388 except FileNotFoundError:
389 print("document.txt file is missing")
390 except PermissionError:
391 print("You are not allowed to read document.txt")
392
R David Murrayf23e2b62012-09-29 19:41:26 -0400393.. seealso::
394
395 :pep:`3151` - Reworking the OS and IO Exception Hierarchy
396 PEP written and implemented by Antoine Pitrou
397
Victor Stinnera1bf2982011-10-12 20:35:02 +0200398
Antoine Pitrouc907de92012-08-21 00:53:06 +0200399.. _pep-380:
400
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000401PEP 380: Syntax for Delegating to a Subgenerator
402================================================
403
404PEP 380 adds the ``yield from`` expression, allowing a generator to delegate
405part of its operations to another generator. This allows a section of code
406containing 'yield' to be factored out and placed in another generator.
407Additionally, the subgenerator is allowed to return with a value, and the
408value is made available to the delegating generator.
Nick Coghlanb9b281b2012-03-06 22:31:12 +1000409
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000410While designed primarily for use in delegating to a subgenerator, the ``yield
411from`` expression actually allows delegation to arbitrary subiterators.
412
Nick Coghlanb9b281b2012-03-06 22:31:12 +1000413For simple iterators, ``yield from iterable`` is essentially just a shortened
414form of ``for item in iterable: yield item``::
415
416 >>> def g(x):
417 ... yield from range(x, 0, -1)
418 ... yield from range(x)
419 ...
420 >>> list(g(5))
421 [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
422
423However, unlike an ordinary loop, ``yield from`` allows subgenerators to
424receive sent and thrown values directly from the calling scope, and
425return a final value to the outer generator::
426
427 >>> def accumulate(start=0):
428 ... tally = start
429 ... while 1:
430 ... next = yield
431 ... if next is None:
432 ... return tally
433 ... tally += next
434 ...
435 >>> def gather_tallies(tallies, start=0):
436 ... while 1:
437 ... tally = yield from accumulate()
438 ... tallies.append(tally)
439 ...
440 >>> tallies = []
441 >>> acc = gather_tallies(tallies)
442 >>> next(acc) # Ensure the accumulator is ready to accept values
443 >>> for i in range(10):
444 ... acc.send(i)
445 ...
446 >>> acc.send(None) # Finish the first tally
447 >>> for i in range(5):
448 ... acc.send(i)
449 ...
450 >>> acc.send(None) # Finish the second tally
451 >>> tallies
452 [45, 10]
453
454The main principle driving this change is to allow even generators that are
455designed to be used with the ``send`` and ``throw`` methods to be split into
456multiple subgenerators as easily as a single large function can be split into
457multiple subfunctions.
458
R David Murrayf23e2b62012-09-29 19:41:26 -0400459.. seealso::
460
461 :pep:`380` - Syntax for Delegating to a Subgenerator
462 PEP written by Greg Ewing; implementation by Greg Ewing, integrated into
Ezio Melotti76e7ea52012-10-20 22:53:47 +0300463 3.3 by Renaud Blanch, Ryan Kelly and Nick Coghlan; documentation by
464 Zbigniew Jędrzejewski-Szmek and Nick Coghlan
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000465
466
Nick Coghlanab7bf212012-02-26 17:49:52 +1000467PEP 409: Suppressing exception context
468======================================
469
Nick Coghlanab7bf212012-02-26 17:49:52 +1000470PEP 409 introduces new syntax that allows the display of the chained
471exception context to be disabled. This allows cleaner error messages in
472applications that convert between exception types::
473
474 >>> class D:
475 ... def __init__(self, extra):
476 ... self._extra_attributes = extra
477 ... def __getattr__(self, attr):
478 ... try:
479 ... return self._extra_attributes[attr]
480 ... except KeyError:
481 ... raise AttributeError(attr) from None
482 ...
483 >>> D({}).x
484 Traceback (most recent call last):
485 File "<stdin>", line 1, in <module>
486 File "<stdin>", line 8, in __getattr__
487 AttributeError: x
488
489Without the ``from None`` suffix to suppress the cause, the original
490exception would be displayed by default::
491
492 >>> class C:
493 ... def __init__(self, extra):
494 ... self._extra_attributes = extra
495 ... def __getattr__(self, attr):
496 ... try:
497 ... return self._extra_attributes[attr]
498 ... except KeyError:
499 ... raise AttributeError(attr)
500 ...
501 >>> C({}).x
502 Traceback (most recent call last):
503 File "<stdin>", line 6, in __getattr__
504 KeyError: 'x'
505
506 During handling of the above exception, another exception occurred:
507
508 Traceback (most recent call last):
509 File "<stdin>", line 1, in <module>
510 File "<stdin>", line 8, in __getattr__
511 AttributeError: x
512
513No debugging capability is lost, as the original exception context remains
514available if needed (for example, if an intervening library has incorrectly
515suppressed valuable underlying details)::
516
517 >>> try:
518 ... D({}).x
519 ... except AttributeError as exc:
520 ... print(repr(exc.__context__))
521 ...
522 KeyError('x',)
523
R David Murrayf23e2b62012-09-29 19:41:26 -0400524.. seealso::
525
526 :pep:`409` - Suppressing exception context
527 PEP written by Ethan Furman; implemented by Ethan Furman and Nick
528 Coghlan.
529
Nick Coghlanab7bf212012-02-26 17:49:52 +1000530
Nick Coghlan98e20702012-03-06 21:50:13 +1000531PEP 414: Explicit Unicode literals
532======================================
533
Nick Coghlan98e20702012-03-06 21:50:13 +1000534To ease the transition from Python 2 for Unicode aware Python applications
535that make heavy use of Unicode literals, Python 3.3 once again supports the
536"``u``" prefix for string literals. This prefix has no semantic significance
537in Python 3, it is provided solely to reduce the number of purely mechanical
538changes in migrating to Python 3, making it easier for developers to focus on
539the more significant semantic changes (such as the stricter default
540separation of binary and text data).
541
R David Murrayf23e2b62012-09-29 19:41:26 -0400542.. seealso::
543
544 :pep:`414` - Explicit Unicode literals
545 PEP written by Armin Ronacher.
546
Nick Coghlan98e20702012-03-06 21:50:13 +1000547
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100548PEP 3155: Qualified name for classes and functions
549==================================================
550
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100551Functions and class objects have a new ``__qualname__`` attribute representing
552the "path" from the module top-level to their definition. For global functions
553and classes, this is the same as ``__name__``. For other functions and classes,
554it provides better information about where they were actually defined, and
555how they might be accessible from the global scope.
556
557Example with (non-bound) methods::
Nick Coghlan2dfe6b02012-01-14 14:19:49 +1000558
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100559 >>> class C:
560 ... def meth(self):
561 ... pass
562 >>> C.meth.__name__
563 'meth'
564 >>> C.meth.__qualname__
565 'C.meth'
566
567Example with nested classes::
568
569 >>> class C:
570 ... class D:
571 ... def meth(self):
572 ... pass
573 ...
574 >>> C.D.__name__
575 'D'
576 >>> C.D.__qualname__
577 'C.D'
578 >>> C.D.meth.__name__
579 'meth'
580 >>> C.D.meth.__qualname__
581 'C.D.meth'
582
583Example with nested functions::
584
585 >>> def outer():
586 ... def inner():
587 ... pass
588 ... return inner
589 ...
590 >>> outer().__name__
591 'inner'
592 >>> outer().__qualname__
593 'outer.<locals>.inner'
594
Antoine Pitroue7ede062011-11-25 19:11:26 +0100595The string representation of those objects is also changed to include the
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100596new, more precise information::
597
598 >>> str(C.D)
599 "<class '__main__.C.D'>"
600 >>> str(C.D.meth)
601 '<function C.D.meth at 0x7f46b9fe31e0>'
602
R David Murrayf23e2b62012-09-29 19:41:26 -0400603.. seealso::
604
605 :pep:`3155` - Qualified name for classes and functions
606 PEP written and implemented by Antoine Pitrou.
607
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100608
Antoine Pitrouc907de92012-08-21 00:53:06 +0200609.. _pep-412:
610
Antoine Pitroud94adb72012-07-07 17:33:42 +0200611PEP 412: Key-Sharing Dictionary
612===============================
613
Antoine Pitroud94adb72012-07-07 17:33:42 +0200614Dictionaries used for the storage of objects' attributes are now able to
615share part of their internal storage between each other (namely, the part
616which stores the keys and their respective hashes). This reduces the memory
617consumption of programs creating many instances of non-builtin types.
618
R David Murrayf23e2b62012-09-29 19:41:26 -0400619.. seealso::
620
621 :pep:`412` - Key-Sharing Dictionary
622 PEP written and implemented by Mark Shannon.
623
Antoine Pitroud94adb72012-07-07 17:33:42 +0200624
Andrew Svetlovac23c9e2012-08-13 21:27:56 +0300625PEP 362: Function Signature Object
626==================================
627
Andrew Svetlovac23c9e2012-08-13 21:27:56 +0300628A new function :func:`inspect.signature` makes introspection of python
629callables easy and straightforward. A broad range of callables is supported:
630python functions, decorated or not, classes, and :func:`functools.partial`
631objects. New classes :class:`inspect.Signature`, :class:`inspect.Parameter`
632and :class:`inspect.BoundArguments` hold information about the call signatures,
633such as, annotations, default values, parameters kinds, and bound arguments,
634which considerably simplifies writing decorators and any code that validates
635or amends calling signatures or arguments.
636
R David Murrayf23e2b62012-09-29 19:41:26 -0400637.. seealso::
638
639 :pep:`362`: - Function Signature Object
640 PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo;
641 implemented by Yury Selivanov.
642
Andrew Svetlovac23c9e2012-08-13 21:27:56 +0300643
Eric Snowb2a61e12012-09-05 22:19:38 -0700644PEP 421: Adding sys.implementation
645==================================
646
Eric Snowb2a61e12012-09-05 22:19:38 -0700647A new attribute on the :mod:`sys` module exposes details specific to the
648implementation of the currently running interpreter. The initial set of
649attributes on :attr:`sys.implementation` are ``name``, ``version``,
650``hexversion``, and ``cache_tag``.
651
652The intention of ``sys.implementation`` is to consolidate into one namespace
653the implementation-specific data used by the standard library. This allows
654different Python implementations to share a single standard library code base
655much more easily. In its initial state, ``sys.implementation`` holds only a
656small portion of the implementation-specific data. Over time that ratio will
657shift in order to make the standard library more portable.
658
659One example of improved standard library portability is ``cache_tag``. As of
660Python 3.3, ``sys.implementation.cache_tag`` is used by :mod:`importlib` to
661support :pep:`3147` compliance. Any Python implementation that uses
662``importlib`` for its built-in import system may use ``cache_tag`` to control
663the caching behavior for modules.
664
665SimpleNamespace
666---------------
667
668The implementation of ``sys.implementation`` also introduces a new type to
669Python: :class:`types.SimpleNamespace`. In contrast to a mapping-based
670namespace, like :class:`dict`, ``SimpleNamespace`` is attribute-based, like
671:class:`object`. However, unlike ``object``, ``SimpleNamespace`` instances
672are writable. This means that you can add, remove, and modify the namespace
673through normal attribute access.
674
R David Murrayf23e2b62012-09-29 19:41:26 -0400675.. seealso::
676
677 :pep:`421` - Adding sys.implementation
678 PEP written and implemented by Eric Snow.
679
Eric Snowb2a61e12012-09-05 22:19:38 -0700680
Antoine Pitrouc907de92012-08-21 00:53:06 +0200681.. _importlib:
682
Brett Cannonc2043482012-04-29 20:59:41 -0400683Using importlib as the Implementation of Import
684===============================================
685:issue:`2377` - Replace __import__ w/ importlib.__import__
686:issue:`13959` - Re-implement parts of :mod:`imp` in pure Python
687:issue:`14605` - Make import machinery explicit
688:issue:`14646` - Require loaders set __loader__ and __package__
689
Brett Cannonc2043482012-04-29 20:59:41 -0400690The :func:`__import__` function is now powered by :func:`importlib.__import__`.
691This work leads to the completion of "phase 2" of :pep:`302`. There are
692multiple benefits to this change. First, it has allowed for more of the
693machinery powering import to be exposed instead of being implicit and hidden
694within the C code. It also provides a single implementation for all Python VMs
695supporting Python 3.3 to use, helping to end any VM-specific deviations in
696import semantics. And finally it eases the maintenance of import, allowing for
697future growth to occur.
698
R David Murraycff1c6f2012-09-29 14:34:43 -0400699For the common user, there should be no visible change in semantics. For
700those whose code currently manipulates import or calls import
701programmatically, the code changes that might possibly be required are covered
702in the `Porting Python code`_ section of this document.
Brett Cannonc2043482012-04-29 20:59:41 -0400703
704New APIs
705--------
706One of the large benefits of this work is the exposure of what goes into
707making the import statement work. That means the various importers that were
708once implicit are now fully exposed as part of the :mod:`importlib` package.
709
Brett Cannon077ef452012-08-02 17:50:06 -0400710The abstract base classes defined in :mod:`importlib.abc` have been expanded
711to properly delineate between :term:`meta path finders <meta path finder>`
712and :term:`path entry finders <path entry finder>` by introducing
713:class:`importlib.abc.MetaPathFinder` and
714:class:`importlib.abc.PathEntryFinder`, respectively. The old ABC of
715:class:`importlib.abc.Finder` is now only provided for backwards-compatibility
716and does not enforce any method requirements.
717
718In terms of finders, :class:`importlib.machinery.FileFinder` exposes the
Brett Cannonc2043482012-04-29 20:59:41 -0400719mechanism used to search for source and bytecode files of a module. Previously
720this class was an implicit member of :attr:`sys.path_hooks`.
721
722For loaders, the new abstract base class :class:`importlib.abc.FileLoader` helps
723write a loader that uses the file system as the storage mechanism for a module's
724code. The loader for source files
725(:class:`importlib.machinery.SourceFileLoader`), sourceless bytecode files
726(:class:`importlib.machinery.SourcelessFileLoader`), and extension modules
727(:class:`importlib.machinery.ExtensionFileLoader`) are now available for
728direct use.
729
730:exc:`ImportError` now has ``name`` and ``path`` attributes which are set when
731there is relevant data to provide. The message for failed imports will also
732provide the full name of the module now instead of just the tail end of the
733module's name.
734
735The :func:`importlib.invalidate_caches` function will now call the method with
736the same name on all finders cached in :attr:`sys.path_importer_cache` to help
737clean up any stored state as necessary.
738
739Visible Changes
740---------------
R David Murrayf23e2b62012-09-29 19:41:26 -0400741
742For potential required changes to code, see the `Porting Python code`_
743section.
Brett Cannonc2043482012-04-29 20:59:41 -0400744
745Beyond the expanse of what :mod:`importlib` now exposes, there are other
746visible changes to import. The biggest is that :attr:`sys.meta_path` and
Brett Cannon077ef452012-08-02 17:50:06 -0400747:attr:`sys.path_hooks` now store all of the meta path finders and path entry
748hooks used by import. Previously the finders were implicit and hidden within
749the C code of import instead of being directly exposed. This means that one can
750now easily remove or change the order of the various finders to fit one's needs.
Brett Cannonc2043482012-04-29 20:59:41 -0400751
752Another change is that all modules have a ``__loader__`` attribute, storing the
753loader used to create the module. :pep:`302` has been updated to make this
754attribute mandatory for loaders to implement, so in the future once 3rd-party
755loaders have been updated people will be able to rely on the existence of the
756attribute. Until such time, though, import is setting the module post-load.
757
758Loaders are also now expected to set the ``__package__`` attribute from
759:pep:`366`. Once again, import itself is already setting this on all loaders
760from :mod:`importlib` and import itself is setting the attribute post-load.
761
762``None`` is now inserted into :attr:`sys.path_importer_cache` when no finder
763can be found on :attr:`sys.path_hooks`. Since :class:`imp.NullImporter` is not
764directly exposed on :attr:`sys.path_hooks` it could no longer be relied upon to
765always be available to use as a value representing no finder found.
766
767All other changes relate to semantic changes which should be taken into
768consideration when updating code for Python 3.3, and thus should be read about
769in the `Porting Python code`_ section of this document.
770
R David Murrayf23e2b62012-09-29 19:41:26 -0400771(Implementation by Brett Cannon)
772
Brett Cannonc2043482012-04-29 20:59:41 -0400773
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000774Other Language Changes
775======================
776
777Some smaller changes made to the core Python language are:
778
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100779* Added support for Unicode name aliases and named sequences.
780 Both :func:`unicodedata.lookup()` and ``'\N{...}'`` now resolve name aliases,
781 and :func:`unicodedata.lookup()` resolves named sequences too.
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000782
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100783 (Contributed by Ezio Melotti in :issue:`12753`)
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300784
Nick Coghlanc4bacd32012-09-27 19:58:31 +1000785* Unicode database updated to UCD version 6.1.0
786
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100787* Equality comparisons on :func:`range` objects now return a result reflecting
788 the equality of the underlying sequences generated by those range objects.
Sandro Tosicd899122012-01-22 12:16:04 +0100789 (:issue:`13201`)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000790
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100791* The ``count()``, ``find()``, ``rfind()``, ``index()`` and ``rindex()``
792 methods of :class:`bytes` and :class:`bytearray` objects now accept an
793 integer between 0 and 255 as their first argument.
Mark Dickinson36645682011-10-23 19:53:01 +0100794
Petri Lehtinen6c3f1dd2012-06-26 10:23:07 +0300795 (Contributed by Petri Lehtinen in :issue:`12170`)
Mark Dickinson36645682011-10-23 19:53:01 +0100796
R David Murraye54c7182012-10-16 21:52:24 -0400797* The ``rjust()``, ``ljust()``, and ``center()`` methods of :class:`bytes`
798 and :class:`bytearray` now accept a :class:`bytearray` for the ``fill``
799 argument. (Contributed by Petri Lehtinen in :issue:`12380`.)
800
Eli Bendersky7add4ea2012-03-17 15:14:35 +0200801* New methods have been added to :class:`list` and :class:`bytearray`:
R David Murrayd2489cf2012-09-30 17:28:54 -0400802 ``copy()`` and ``clear()`` (:issue:`10516`). Consequently,
803 :class:`~collections.abc.MutableSequence` now also defines a
804 :meth:`~collections.abc.MutableSequence.clear` method (:issue:`11388`).
Petri Lehtinen61ea8a02011-11-24 22:00:46 +0200805
Antoine Pitrou9a864472012-05-04 23:15:47 +0200806* Raw bytes literals can now be written ``rb"..."`` as well as ``br"..."``.
R David Murrayf23e2b62012-09-29 19:41:26 -0400807
Antoine Pitrou9a864472012-05-04 23:15:47 +0200808 (Contributed by Antoine Pitrou in :issue:`13748`.)
809
810* :meth:`dict.setdefault` now does only one lookup for the given key, making
811 it atomic when used with built-in types.
R David Murrayf23e2b62012-09-29 19:41:26 -0400812
Antoine Pitrou9a864472012-05-04 23:15:47 +0200813 (Contributed by Filip Gruszczyński in :issue:`13521`.)
814
R David Murrayf23e2b62012-09-29 19:41:26 -0400815* The error messages produced when a function call does not match the function
816 signature have been significantly improved.
Antoine Pitrou9a864472012-05-04 23:15:47 +0200817
R David Murrayf23e2b62012-09-29 19:41:26 -0400818 (Contributed by Benjamin Peterson.)
Benjamin Petersone50d6ab2012-04-03 00:52:18 -0400819
Antoine Pitrou9a864472012-05-04 23:15:47 +0200820
Antoine Pitrou79341e72012-05-17 21:13:45 +0200821A Finer-Grained Import Lock
822===========================
823
824Previous versions of CPython have always relied on a global import lock.
825This led to unexpected annoyances, such as deadlocks when importing a module
826would trigger code execution in a different thread as a side-effect.
827Clumsy workarounds were sometimes employed, such as the
828:c:func:`PyImport_ImportModuleNoBlock` C API function.
829
830In Python 3.3, importing a module takes a per-module lock. This correctly
831serializes importation of a given module from multiple threads (preventing
832the exposure of incompletely initialized modules), while eliminating the
833aforementioned annoyances.
834
R David Murrayf23e2b62012-09-29 19:41:26 -0400835(Contributed by Antoine Pitrou in :issue:`9260`.)
Antoine Pitrou79341e72012-05-17 21:13:45 +0200836
837
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200838Builtin functions and types
839===========================
Victor Stinnerfa0d6282012-08-05 15:56:51 +0200840
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200841* :func:`open` gets a new *opener* parameter: the underlying file descriptor
842 for the file object is then obtained by calling *opener* with (*file*,
843 *flags*). It can be used to use custom flags like :data:`os.O_CLOEXEC` for
844 example. The ``'x'`` mode was added: open for exclusive creation, failing if
845 the file already exists.
846* :func:`print`: added the *flush* keyword argument. If the *flush* keyword
847 argument is true, the stream is forcibly flushed.
848* :func:`hash`: hash randomization is enabled by default, see
849 :meth:`object.__hash__` and :envvar:`PYTHONHASHSEED`.
850* The :class:`str` type gets a new :meth:`~str.casefold` method: return a
851 casefolded copy of the string, casefolded strings may be used for caseless
852 matching. For example, ``'ß'.casefold()`` returns ``'ss'``.
Nick Coghlan273069c2012-08-20 17:14:07 +1000853* The sequence documentation has been substantially rewritten to better
854 explain the binary/text sequence distinction and to provide specific
855 documentation sections for the individual builtin sequence types
856 (:issue:`4966`)
Victor Stinnerfa0d6282012-08-05 15:56:51 +0200857
R David Murrayf23e2b62012-09-29 19:41:26 -0400858
Victor Stinner636130e2012-08-05 16:37:12 +0200859New Modules
860===========
861
862faulthandler
863------------
864
Victor Stinner1da769a2012-09-18 22:40:03 +0200865This new debug module :mod:`faulthandler` contains functions to dump Python tracebacks explicitly,
Victor Stinner636130e2012-08-05 16:37:12 +0200866on a fault (a crash like a segmentation fault), after a timeout, or on a user
867signal. Call :func:`faulthandler.enable` to install fault handlers for the
868:const:`SIGSEGV`, :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS`, and
869:const:`SIGILL` signals. You can also enable them at startup by setting the
870:envvar:`PYTHONFAULTHANDLER` environment variable or by using :option:`-X`
871``faulthandler`` command line option.
872
873Example of a segmentation fault on Linux: ::
874
875 $ python -q -X faulthandler
876 >>> import ctypes
877 >>> ctypes.string_at(0)
878 Fatal Python error: Segmentation fault
879
880 Current thread 0x00007fb899f39700:
881 File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
882 File "<stdin>", line 1 in <module>
883 Segmentation fault
884
885
886ipaddress
887---------
888
889The new :mod:`ipaddress` module provides tools for creating and manipulating
890objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e.
891an IP address associated with a specific IP subnet).
892
893(Contributed by Google and Peter Moody in :pep:`3144`)
894
895lzma
896----
897
898The newly-added :mod:`lzma` module provides data compression and decompression
899using the LZMA algorithm, including support for the ``.xz`` and ``.lzma``
900file formats.
901
902(Contributed by Nadeem Vawda and Per Øyvind Karlsen in :issue:`6715`)
903
904
905Improved Modules
906================
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000907
Victor Stinnerf4c54ff2012-02-08 01:48:34 +0100908abc
909---
910
911Improved support for abstract base classes containing descriptors composed with
912abstract methods. The recommended approach to declaring abstract descriptors is
913now to provide :attr:`__isabstractmethod__` as a dynamically updated
914property. The built-in descriptors have been updated accordingly.
915
916 * :class:`abc.abstractproperty` has been deprecated, use :class:`property`
917 with :func:`abc.abstractmethod` instead.
918 * :class:`abc.abstractclassmethod` has been deprecated, use
919 :class:`classmethod` with :func:`abc.abstractmethod` instead.
920 * :class:`abc.abstractstaticmethod` has been deprecated, use
921 :class:`staticmethod` with :func:`abc.abstractmethod` instead.
922
923(Contributed by Darren Dale in :issue:`11610`)
924
R David Murrayd2489cf2012-09-30 17:28:54 -0400925:meth:`abc.ABCMeta.register` now returns the registered subclass, which means
926it can now be used as a class decorator (:issue:`10868`).
927
928
Meador Ingec5dbb3d2011-09-20 21:48:16 -0500929array
930-----
931
932The :mod:`array` module supports the :c:type:`long long` type using ``q`` and
933``Q`` type codes.
934
935(Contributed by Oren Tirosh and Hirokazu Yamamoto in :issue:`1172711`)
936
937
R David Murrayf4c27572012-10-06 23:19:17 -0400938base64
939------
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200940
941ASCII-only Unicode strings are now accepted by the decoding functions of the
R David Murrayf4c27572012-10-06 23:19:17 -0400942:mod:`base64` modern interface. For example, ``base64.b64decode('YWJj')``
943returns ``b'abc'``. (Contributed by Catalin Iacob in :issue:`13641`.)
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200944
945
R David Murrayfd740962012-10-06 22:08:08 -0400946binascii
947--------
948
949In addition to the binary objects they normally accept, the ``a2b_`` functions
950now all also accept ASCII-only strings as input. (Contributed by Antoine
951Pitrou in :issue:`13637`.)
952
953
Nadeem Vawdad7e5c6e2012-02-12 01:34:18 +0200954bz2
955---
956
957The :mod:`bz2` module has been rewritten from scratch. In the process, several
958new features have been added:
959
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200960* New :func:`bz2.open` function: open a bzip2-compressed file in binary or
961 text mode.
962
Nadeem Vawdad7e5c6e2012-02-12 01:34:18 +0200963* :class:`bz2.BZ2File` can now read from and write to arbitrary file-like
964 objects, by means of its constructor's *fileobj* argument.
965
966 (Contributed by Nadeem Vawda in :issue:`5863`)
967
968* :class:`bz2.BZ2File` and :func:`bz2.decompress` can now decompress
969 multi-stream inputs (such as those produced by the :program:`pbzip2` tool).
970 :class:`bz2.BZ2File` can now also be used to create this type of file, using
971 the ``'a'`` (append) mode.
972
973 (Contributed by Nir Aides in :issue:`1625`)
974
975* :class:`bz2.BZ2File` now implements all of the :class:`io.BufferedIOBase` API,
976 except for the :meth:`detach` and :meth:`truncate` methods.
977
978
Victor Stinner2cded9c2011-07-08 01:45:13 +0200979codecs
980------
981
Antoine Pitrou4f863432012-02-12 02:12:47 +0100982The :mod:`~encodings.mbcs` codec has been rewritten to handle correctly
Georg Brandlff962c52012-02-04 08:55:56 +0100983``replace`` and ``ignore`` error handlers on all Windows versions. The
984:mod:`~encodings.mbcs` codec now supports all error handlers, instead of only
985``replace`` to encode and ``ignore`` to decode.
Victor Stinner3a50e702011-10-18 21:21:00 +0200986
Georg Brandlff962c52012-02-04 08:55:56 +0100987A new Windows-only codec has been added: ``cp65001`` (:issue:`13216`). It is the
988Windows code page 65001 (Windows UTF-8, ``CP_UTF8``). For example, it is used
989by ``sys.stdout`` if the console output code page is set to cp65001 (e.g., using
990``chcp 65001`` command).
Victor Stinner2f3ca9f2011-10-27 01:38:56 +0200991
Georg Brandlff962c52012-02-04 08:55:56 +0100992Multibyte CJK decoders now resynchronize faster. They only ignore the first
Georg Brandl6c0929b2011-07-09 11:43:33 +0200993byte of an invalid byte sequence. For example, ``b'\xff\n'.decode('gb2312',
994'replace')`` now returns a ``\n`` after the replacement character.
Victor Stinner2cded9c2011-07-08 01:45:13 +0200995
Georg Brandl6c0929b2011-07-09 11:43:33 +0200996(:issue:`12016`)
Victor Stinner2cded9c2011-07-08 01:45:13 +0200997
Georg Brandlff962c52012-02-04 08:55:56 +0100998Incremental CJK codec encoders are no longer reset at each call to their
999encode() methods. For example::
Victor Stinner2cded9c2011-07-08 01:45:13 +02001000
1001 $ ./python -q
1002 >>> import codecs
1003 >>> encoder = codecs.getincrementalencoder('hz')('strict')
1004 >>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
1005 b'~{NpJ)l6HK!#~} Bye.'
1006
Georg Brandl6c0929b2011-07-09 11:43:33 +02001007This example gives ``b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.'`` with older Python
Victor Stinner2cded9c2011-07-08 01:45:13 +02001008versions.
1009
Georg Brandl6c0929b2011-07-09 11:43:33 +02001010(:issue:`12100`)
Victor Stinner2cded9c2011-07-08 01:45:13 +02001011
Victor Stinner9f4b1e92011-11-10 20:56:30 +01001012The ``unicode_internal`` codec has been deprecated.
1013
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001014
1015collections
1016-----------
1017
1018Addition of a new :class:`~collections.ChainMap` class to allow treating a
R David Murraya21e5152012-10-06 16:29:14 -04001019number of mappings as a single unit. (Written by Raymond Hettinger for
1020:issue:`11089`, made public in :issue:`11297`)
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001021
1022The abstract base classes have been moved in a new :mod:`collections.abc`
1023module, to better differentiate between the abstract and the concrete
1024collections classes. Aliases for ABCs are still present in the
R David Murraya21e5152012-10-06 16:29:14 -04001025:mod:`collections` module to preserve existing imports. (:issue:`11085`)
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001026
1027.. XXX addition of __slots__ to ABCs not recorded here: internal detail
1028
R David Murraya21e5152012-10-06 16:29:14 -04001029The :class:`~collections.Counter` class now supports the unary ``+`` and ``-``
1030operators, as well as the in-place operators ``+=``, ``-=``, ``|=``, and
1031``&=``. (Contributed by Raymond Hettinger in :issue:`13121`.)
1032
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001033
Nick Coghlan3267a302012-05-21 22:54:43 +10001034contextlib
1035----------
1036
Giampaolo Rodola'15c88492012-09-25 12:00:04 -07001037:class:`~contextlib.ExitStack` now provides a solid foundation for
Nick Coghlan3267a302012-05-21 22:54:43 +10001038programmatic manipulation of context managers and similar cleanup
1039functionality. Unlike the previous ``contextlib.nested`` API (which was
1040deprecated and removed), the new API is designed to work correctly
1041regardless of whether context managers acquire their resources in
Nick Coghlan161ea6a2012-05-22 23:04:42 +10001042their ``__init__`` method (for example, file objects) or in their
Nick Coghlan3267a302012-05-21 22:54:43 +10001043``__enter__`` method (for example, synchronisation objects from the
1044:mod:`threading` module).
1045
1046(:issue:`13585`)
1047
1048
Éric Araujo84b8ed82011-08-29 21:42:47 +02001049crypt
1050-----
1051
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001052Addition of salt and modular crypt format (hashing method) and the :func:`~crypt.mksalt`
Victor Stinnerc78fb332011-09-21 03:35:44 +02001053function to the :mod:`crypt` module.
Éric Araujo84b8ed82011-08-29 21:42:47 +02001054
1055(:issue:`10924`)
1056
Victor Stinnera7878b72011-07-14 23:07:44 +02001057curses
1058------
1059
Victor Stinner0fdfceb2011-11-25 22:10:02 +01001060 * If the :mod:`curses` module is linked to the ncursesw library, use Unicode
1061 functions when Unicode strings or characters are passed (e.g.
1062 :c:func:`waddwstr`), and bytes functions otherwise (e.g. :c:func:`waddstr`).
1063 * Use the locale encoding instead of ``utf-8`` to encode Unicode strings.
1064 * :class:`curses.window` has a new :attr:`curses.window.encoding` attribute.
Victor Stinnerc78fb332011-09-21 03:35:44 +02001065 * The :class:`curses.window` class has a new :meth:`~curses.window.get_wch`
1066 method to get a wide character
1067 * The :mod:`curses` module has a new :meth:`~curses.unget_wch` function to
1068 push a wide character so the next :meth:`~curses.window.get_wch` will return
1069 it
Victor Stinnera7878b72011-07-14 23:07:44 +02001070
Victor Stinnerc78fb332011-09-21 03:35:44 +02001071(Contributed by Iñigo Serna in :issue:`6755`)
Victor Stinnera7878b72011-07-14 23:07:44 +02001072
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001073datetime
1074--------
1075
1076 * Equality comparisons between naive and aware :class:`~datetime.datetime`
R David Murrayd2489cf2012-09-30 17:28:54 -04001077 instances now return :const:`False` instead of raising :exc:`TypeError`
1078 (:issue:`15006`).
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001079 * New :meth:`datetime.datetime.timestamp` method: Return POSIX timestamp
1080 corresponding to the :class:`~datetime.datetime` instance.
1081 * The :meth:`datetime.datetime.strftime` method supports formatting years
1082 older than 1000.
R David Murraydefdb162012-09-29 10:53:31 -04001083 * The :meth:`datetime.datetime.astimezone` method can now be
Alexander Belopolsky35d600c2012-08-22 23:14:29 -04001084 called without arguments to convert datetime instance to the system
1085 timezone.
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001086
R David Murrayf23e2b62012-09-29 19:41:26 -04001087
1088.. _new-decimal:
1089
Stefan Krah1919b7e2012-03-21 18:25:23 +01001090decimal
1091-------
1092
1093:issue:`7652` - integrate fast native decimal arithmetic.
1094 C-module and libmpdec written by Stefan Krah.
1095
1096The new C version of the decimal module integrates the high speed libmpdec
Stefan Krahbf803082012-04-01 13:07:24 +02001097library for arbitrary precision correctly-rounded decimal floating point
1098arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001099
Stefan Krah0c0914e2012-04-09 20:31:15 +02001100Performance gains range from 10x for database applications to 100x for
Stefan Krahbf803082012-04-01 13:07:24 +02001101numerically intensive applications. These numbers are expected gains
1102for standard precisions used in decimal floating point arithmetic. Since
1103the precision is user configurable, the exact figures may vary. For example,
1104in integer bignum arithmetic the differences can be significantly higher.
1105
1106The following table is meant as an illustration. Benchmarks are available
Georg Brandl204e7892012-04-01 13:10:58 +02001107at http://www.bytereef.org/mpdecimal/quickstart.html.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001108
1109 +---------+-------------+--------------+-------------+
1110 | | decimal.py | _decimal | speedup |
1111 +=========+=============+==============+=============+
Stefan Kraha3f4a162012-09-01 14:27:51 +02001112 | pi | 42.02s | 0.345s | 120x |
Stefan Krah1919b7e2012-03-21 18:25:23 +01001113 +---------+-------------+--------------+-------------+
1114 | telco | 172.19s | 5.68s | 30x |
1115 +---------+-------------+--------------+-------------+
1116 | psycopg | 3.57s | 0.29s | 12x |
1117 +---------+-------------+--------------+-------------+
1118
1119Features
1120~~~~~~~~
1121
1122* The :exc:`~decimal.FloatOperation` signal optionally enables stricter
1123 semantics for mixing floats and Decimals.
1124
1125* If Python is compiled without threads, the C version automatically
1126 disables the expensive thread local context machinery. In this case,
1127 the variable :data:`~decimal.HAVE_THREADS` is set to False.
1128
1129API changes
1130~~~~~~~~~~~
1131
1132* The C module has the following context limits, depending on the machine
1133 architecture:
1134
1135 +-------------------+---------------------+------------------------------+
1136 | | 32-bit | 64-bit |
1137 +===================+=====================+==============================+
1138 | :const:`MAX_PREC` | :const:`425000000` | :const:`999999999999999999` |
1139 +-------------------+---------------------+------------------------------+
1140 | :const:`MAX_EMAX` | :const:`425000000` | :const:`999999999999999999` |
1141 +-------------------+---------------------+------------------------------+
1142 | :const:`MIN_EMIN` | :const:`-425000000` | :const:`-999999999999999999` |
1143 +-------------------+---------------------+------------------------------+
1144
1145* In the context templates (:class:`~decimal.DefaultContext`,
1146 :class:`~decimal.BasicContext` and :class:`~decimal.ExtendedContext`)
1147 the magnitude of :attr:`~decimal.Context.Emax` and
1148 :attr:`~decimal.Context.Emin` has changed to :const:`999999`.
1149
1150* The :class:`~decimal.Decimal` constructor in decimal.py does not observe
1151 the context limits and converts values with arbitrary exponents or precision
1152 exactly. Since the C version has internal limits, the following scheme is
1153 used: If possible, values are converted exactly, otherwise
1154 :exc:`~decimal.InvalidOperation` is raised and the result is NaN. In the
1155 latter case it is always possible to use :meth:`~decimal.Context.create_decimal`
1156 in order to obtain a rounded or inexact value.
1157
1158
1159* The power function in decimal.py is always correctly-rounded. In the
1160 C version, it is defined in terms of the correctly-rounded
1161 :meth:`~decimal.Decimal.exp` and :meth:`~decimal.Decimal.ln` functions,
1162 but the final result is only "almost always correctly rounded".
1163
1164
1165* In the C version, the context dictionary containing the signals is a
1166 :class:`~collections.abc.MutableMapping`. For speed reasons,
1167 :attr:`~decimal.Context.flags` and :attr:`~decimal.Context.traps` always
1168 refer to the same :class:`~collections.abc.MutableMapping` that the context
1169 was initialized with. If a new signal dictionary is assigned,
1170 :attr:`~decimal.Context.flags` and :attr:`~decimal.Context.traps`
1171 are updated with the new values, but they do not reference the RHS
1172 dictionary.
1173
1174
1175* Pickling a :class:`~decimal.Context` produces a different output in order
1176 to have a common interchange format for the Python and C versions.
1177
1178
1179* The order of arguments in the :class:`~decimal.Context` constructor has been
1180 changed to match the order displayed by :func:`repr`.
1181
1182
Stefan Krahaf3f3a72012-08-30 12:33:55 +02001183* The ``watchexp`` parameter in the :meth:`~decimal.Decimal.quantize` method
1184 is deprecated.
1185
1186
R David Murrayf23e2b62012-09-29 19:41:26 -04001187.. _new-email:
1188
R David Murray77ac3512012-09-29 15:43:33 -04001189email
1190-----
1191
1192Policy Framework
1193~~~~~~~~~~~~~~~~
1194
1195The email package now has a :mod:`~email.policy` framework. A
1196:class:`~email.policy.Policy` is an object with several methods and properties
1197that control how the email package behaves. The primary policy for Python 3.3
1198is the :class:`~email.policy.Compat32` policy, which provides backward
1199compatibility with the email package in Python 3.2. A ``policy`` can be
1200specified when an email message is parsed by a :mod:`~email.parser`, or when a
1201:class:`~email.message.Message` object is created, or when an email is
1202serialized using a :mod:`~email.generator`. Unless overridden, a policy passed
1203to a ``parser`` is inherited by all the ``Message`` object and sub-objects
1204created by the ``parser``. By default a ``generator`` will use the policy of
1205the ``Message`` object it is serializing. The default policy is
1206:data:`~email.policy.compat32`.
1207
1208The minimum set of controls implemented by all ``policy`` objects are:
1209
1210 =============== =======================================================
1211 max_line_length The maximum length, excluding the linesep character(s),
1212 individual lines may have when a ``Message`` is
1213 serialized. Defaults to 78.
1214
1215 linesep The character used to separate individual lines when a
1216 ``Message`` is serialized. Defaults to ``\n``.
1217
1218 cte_type ``7bit`` or ``8bit``. ``8bit`` applies only to a
1219 ``Bytes`` ``generator``, and means that non-ASCII may
1220 be used where allowed by the protocol (or where it
1221 exists in the original input).
1222
1223 raise_on_defect Causes a ``parser`` to raise error when defects are
1224 encountered instead of adding them to the ``Message``
1225 object's ``defects`` list.
1226 =============== =======================================================
1227
1228A new policy instance, with new settings, is created using the
1229:meth:`~email.policy.Policy.clone` method of policy objects. ``clone`` takes
1230any of the above controls as keyword arguments. Any control not specified in
1231the call retains its default value. Thus you can create a policy that uses
1232``\r\n`` linesep characters like this::
1233
1234 mypolicy = compat32.clone(linesep='\r\n')
1235
1236Policies can be used to make the generation of messages in the format needed by
1237your application simpler. Instead of having to remember to specify
1238``linesep='\r\n'`` in all the places you call a ``generator``, you can specify
1239it once, when you set the policy used by the ``parser`` or the ``Message``,
1240whichever your program uses to create ``Message`` objects. On the other hand,
1241if you need to generate messages in multiple forms, you can still specify the
1242parameters in the appropriate ``generator`` call. Or you can have custom
1243policy instances for your different cases, and pass those in when you create
1244the ``generator``.
1245
1246
1247Provisional Policy with New Header API
1248~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1249
1250While the policy framework is worthwhile all by itself, the main motivation for
1251introducing it is to allow the creation of new policies that implement new
1252features for the email package in a way that maintains backward compatibility
1253for those who do not use the new policies. Because the new policies introduce a
1254new API, we are releasing them in Python 3.3 as a :term:`provisional policy
1255<provisional package>`. Backwards incompatible changes (up to and including
1256removal of the code) may occur if deemed necessary by the core developers.
1257
1258The new policies are instances of :class:`~email.policy.EmailPolicy`,
1259and add the following additional controls:
1260
1261 =============== =======================================================
1262 refold_source Controls whether or not headers parsed by a
1263 :mod:`~email.parser` are refolded by the
1264 :mod:`~email.generator`. It can be ``none``, ``long``,
1265 or ``all``. The default is ``long``, which means that
1266 source headers with a line longer than
1267 ``max_line_length`` get refolded. ``none`` means no
1268 line get refolded, and ``all`` means that all lines
1269 get refolded.
1270
1271 header_factory A callable that take a ``name`` and ``value`` and
1272 produces a custom header object.
1273 =============== =======================================================
1274
1275The ``header_factory`` is the key to the new features provided by the new
1276policies. When one of the new policies is used, any header retrieved from
1277a ``Message`` object is an object produced by the ``header_factory``, and any
1278time you set a header on a ``Message`` it becomes an object produced by
1279``header_factory``. All such header objects have a ``name`` attribute equal
1280to the header name. Address and Date headers have additional attributes
1281that give you access to the parsed data of the header. This means you can now
1282do things like this::
1283
1284 >>> m = Message(policy=SMTP)
1285 >>> m['To'] = 'Éric <foo@example.com>'
1286 >>> m['to']
1287 'Éric <foo@example.com>'
1288 >>> m['to'].addresses
1289 (Address(display_name='Éric', username='foo', domain='example.com'),)
1290 >>> m['to'].addresses[0].username
1291 'foo'
1292 >>> m['to'].addresses[0].display_name
1293 'Éric'
1294 >>> m['Date'] = email.utils.localtime()
1295 >>> m['Date'].datetime
1296 datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
1297 >>> m['Date']
1298 'Fri, 25 May 2012 21:44:27 -0400'
1299 >>> print(m)
1300 To: =?utf-8?q?=C3=89ric?= <foo@example.com>
1301 Date: Fri, 25 May 2012 21:44:27 -0400
1302
1303You will note that the unicode display name is automatically encoded as
1304``utf-8`` when the message is serialized, but that when the header is accessed
1305directly, you get the unicode version. This eliminates any need to deal with
1306the :mod:`email.header` :meth:`~email.header.decode_header` or
1307:meth:`~email.header.make_header` functions.
1308
1309You can also create addresses from parts::
1310
1311 >>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
1312 ... Address('Sally', 'sally', 'example.com')]),
1313 ... Address('Bonzo', addr_spec='bonz@laugh.com')]
1314 >>> print(m)
1315 To: =?utf-8?q?=C3=89ric?= <foo@example.com>
1316 Date: Fri, 25 May 2012 21:44:27 -0400
1317 cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>
1318
1319Decoding to unicode is done automatically::
1320
1321 >>> m2 = message_from_string(str(m))
1322 >>> m2['to']
1323 'Éric <foo@example.com>'
1324
1325When you parse a message, you can use the ``addresses`` and ``groups``
1326attributes of the header objects to access the groups and individual
1327addresses::
1328
1329 >>> m2['cc'].addresses
1330 (Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))
1331 >>> m2['cc'].groups
1332 (Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))
1333
1334In summary, if you use one of the new policies, header manipulation works the
1335way it ought to: your application works with unicode strings, and the email
1336package transparently encodes and decodes the unicode to and from the RFC
1337standard Content Transfer Encodings.
1338
R David Murray445d69c2012-09-30 21:59:56 -04001339Other API Changes
1340~~~~~~~~~~~~~~~~~
1341
R David Murray3430fb82012-10-02 18:24:56 -04001342New :class:`~email.parser.BytesHeaderParser`, added to the :mod:`~email.parser`
1343module to complement :class:`~email.parser.HeaderParser` and complete the Bytes
1344API.
1345
1346New utility functions:
1347
1348 * :func:`~email.utils.format_datetime`: given a :class:`~datetime.datetime`,
1349 produce a string formatted for use in an email header.
1350
1351 * :func:`~email.utils.parsedate_to_datetime`: given a date string from
1352 an email header, convert it into an aware :class:`~datetime.datetime`,
1353 or a naive :class:`~datetime.datetime` if the offset is ``-0000``.
1354
1355 * :func:`~email.utils.localtime`: With no argument, returns the
1356 current local time as an aware :class:`~datetime.datetime` using the local
1357 :class:`~datetime.timezone`. Given an aware :class:`~datetime.datetime`,
1358 converts it into an aware :class:`~datetime.datetime` using the
1359 local :class:`~datetime.timezone`.
R David Murray445d69c2012-09-30 21:59:56 -04001360
R David Murray77ac3512012-09-29 15:43:33 -04001361
Victor Stinner811db3b2011-09-21 03:20:03 +02001362ftplib
1363------
1364
R David Murrayd2489cf2012-09-30 17:28:54 -04001365* :class:`ftplib.FTP` now accepts a ``source_address`` keyword argument to
1366 specify the ``(host, port)`` to use as the source address in the bind call
1367 when creating the outgoing socket. (Contributed by Giampaolo Rodolà
1368 in :issue:`8594`.)
1369
Giampaolo Rodola'49379c02012-09-25 12:32:46 -07001370* The :class:`~ftplib.FTP_TLS` class now provides a new
1371 :func:`~ftplib.FTP_TLS.ccc` function to revert control channel back to
R David Murrayd2489cf2012-09-30 17:28:54 -04001372 plaintext. This can be useful to take advantage of firewalls that know how
1373 to handle NAT with non-secure FTP without opening fixed ports. (Contributed
1374 by Giampaolo Rodolà in :issue:`12139`)
Victor Stinner811db3b2011-09-21 03:20:03 +02001375
Giampaolo Rodola'49379c02012-09-25 12:32:46 -07001376* Added :meth:`ftplib.FTP.mlsd` method which provides a parsable directory
1377 listing format and deprecates :meth:`ftplib.FTP.nlst` and
R David Murrayd2489cf2012-09-30 17:28:54 -04001378 :meth:`ftplib.FTP.dir`. (Contributed by Giampaolo Rodolà in :issue:`11072`)
Victor Stinner811db3b2011-09-21 03:20:03 +02001379
R David Murray1e218c92012-10-06 18:18:55 -04001380
1381functools
1382---------
1383
1384The :func:`functools.lru_cache` decorator now accepts a ``typed`` keyword
1385argument (that defaults to ``False`` to ensure that it caches values of
1386different types that compare equal in separate cache slots. (Contributed
1387by Raymond Hettinger in :issue:`13227`.)
1388
1389
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001390gc
1391--
1392
1393It is now possible to register callbacks invoked by the garbage collector
Georg Brandla81b4812012-08-11 08:43:59 +02001394before and after collection using the new :data:`~gc.callbacks` list.
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001395
1396
Christian Heimes31940372012-06-26 10:16:55 +02001397hmac
1398----
1399
R David Murray1e218c92012-10-06 18:18:55 -04001400A new :func:`~hmac.compare_digest` function has been added to prevent side
1401channel attacks on digests through timing analysis. (Contributed by Nick
1402Coghlan and Christian Heimes in :issue:`15061`)
Ezio Melotti461f41d2012-09-26 17:43:23 +03001403
1404
R David Murray445d69c2012-09-30 21:59:56 -04001405http
1406----
1407
1408:class:`http.server.BaseHTTPRequestHandler` now buffers the headers and writes
1409them all at once when :meth:`~http.server.BaseHTTPRequestHandler.end_headers` is
1410called. A new method :meth:`~http.server.BaseHTTPRequestHandler.flush_headers`
1411can be used to directly manage when the accumlated headers are sent.
1412(Contributed by Andrew Schaaf in :issue:`3709`.)
1413
R David Murray1e218c92012-10-06 18:18:55 -04001414:class:`http.server` now produces valid ``HTML 4.01 strict`` output.
1415(Contributed by Ezio Melotti in :issue:`13295`.)
R David Murray445d69c2012-09-30 21:59:56 -04001416
R David Murrayfd740962012-10-06 22:08:08 -04001417:class:`http.client.HTTPResponse` now has a
1418:meth:`~http.client.HTTPResponse.readinto` method, which means it can be used
1419as a :class:`io.RawIOBase` class. (Contributed by John Kuhn in
1420:issue:`13464`.)
1421
Ezio Melotti461f41d2012-09-26 17:43:23 +03001422
R David Murray1e218c92012-10-06 18:18:55 -04001423html
1424----
1425
1426:class:`html.parser.HTMLParser` is now able to parse broken markup without
Ezio Melotti461f41d2012-09-26 17:43:23 +03001427raising errors, therefore the *strict* argument of the constructor and the
1428:exc:`~html.parser.HTMLParseError` exception are now deprecated.
1429The ability to parse broken markup is the result of a number of bug fixes that
1430are also available on the latest bug fix releases of Python 2.7/3.2.
Ezio Melotti461f41d2012-09-26 17:43:23 +03001431(Contributed by Ezio Melotti in :issue:`15114`, and :issue:`14538`,
1432:issue:`13993`, :issue:`13960`, :issue:`13358`, :issue:`1745761`,
1433:issue:`755670`, :issue:`13357`, :issue:`12629`, :issue:`1200313`,
1434:issue:`670664`, :issue:`13273`, :issue:`12888`, :issue:`7311`)
1435
R David Murray1e218c92012-10-06 18:18:55 -04001436A new :data:`~html.entities.html5` dictionary that maps HTML5 named character
1437references to the equivalent Unicode character(s) (e.g. ``html5['gt;'] ==
1438'>'``) has been added to the :mod:`html.entities` module. The dictionary is
1439now also used by :class:`~html.parser.HTMLParser`. (Contributed by Ezio
1440Melotti in :issue:`11113` and :issue:`15156`)
1441
R David Murray445d69c2012-09-30 21:59:56 -04001442
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01001443imaplib
1444-------
1445
1446The :class:`~imaplib.IMAP4_SSL` constructor now accepts an SSLContext
1447parameter to control parameters of the secure channel.
1448
1449(Contributed by Sijin Joseph in :issue:`8808`)
1450
1451
Nick Coghlan2f92e542012-06-23 19:39:55 +10001452inspect
1453-------
1454
1455A new :func:`~inspect.getclosurevars` function has been added. This function
1456reports the current binding of all names referenced from the function body and
1457where those names were resolved, making it easier to verify correct internal
1458state when testing code that relies on stateful closures.
1459
1460(Contributed by Meador Inge and Nick Coghlan in :issue:`13062`)
1461
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001462A new :func:`~inspect.getgeneratorlocals` function has been added. This
1463function reports the current binding of local variables in the generator's
1464stack frame, making it easier to verify correct internal state when testing
1465generators.
1466
1467(Contributed by Meador Inge in :issue:`15153`)
1468
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001469io
1470--
1471
Charles-François Natalid612de12012-01-14 11:51:00 +01001472The :func:`~io.open` function has a new ``'x'`` mode that can be used to
1473exclusively create a new file, and raise a :exc:`FileExistsError` if the file
1474already exists. It is based on the C11 'x' mode to fopen().
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001475
1476(Contributed by David Townshend in :issue:`12760`)
1477
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001478The constructor of the :class:`~io.TextIOWrapper` class has a new
1479*write_through* optional argument. If *write_through* is ``True``, calls to
1480:meth:`~io.TextIOWrapper.write` are guaranteed not to be buffered: any data
1481written on the :class:`~io.TextIOWrapper` object is immediately handled to its
1482underlying binary buffer.
1483
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001484
R David Murray445d69c2012-09-30 21:59:56 -04001485itertools
1486---------
1487
1488:func:`~itertools.accumulate` now takes an optional ``func`` argument for
1489providing a user-supplied binary function.
1490
1491
1492logging
1493-------
1494
R David Murray3430fb82012-10-02 18:24:56 -04001495The :func:`~logging.basicConfig` function now supports an optional ``handlers``
1496argument taking an iterable of handlers to be added to the root logger.
1497
1498A class level attribute :attr:`~logging.handlers.SysLogHandler.append_nul` has
1499been added to :class:`~logging.handlers.SysLogHandler` to allow control of the
1500appending of the ``NUL`` (``\000``) byte to syslog records, since for some
1501deamons it is required while for others it is passed through to the log.
1502
R David Murray445d69c2012-09-30 21:59:56 -04001503
1504
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001505math
1506----
1507
R David Murray26d15bf2012-09-29 15:13:35 -04001508The :mod:`math` module has a new function, :func:`~math.log2`, which returns
1509the base-2 logarithm of *x*.
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001510
R David Murray26d15bf2012-09-29 15:13:35 -04001511(Written by Mark Dickinson in :issue:`11888`).
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001512
1513
R David Murray3430fb82012-10-02 18:24:56 -04001514mmap
1515----
1516
1517The :meth:`~mmap.mmap.read` method is now more compatible with other file-like
1518objects: if the argument is omitted or specified as ``None``, it returns the
1519bytes from the current file position to the end of the mapping. (Contributed
1520by Petri Lehtinen in :issue:`12021`.)
1521
1522
Antoine Pitrou9a864472012-05-04 23:15:47 +02001523multiprocessing
1524---------------
1525
1526The new :func:`multiprocessing.connection.wait` function allows to poll
1527multiple objects (such as connections, sockets and pipes) with a timeout.
1528(Contributed by Richard Oudkerk in :issue:`12328`.)
1529
1530:class:`multiprocessing.Connection` objects can now be transferred over
1531multiprocessing connections.
1532(Contributed by Richard Oudkerk in :issue:`4892`.)
1533
R David Murrayd2489cf2012-09-30 17:28:54 -04001534:class:`multiprocessing.Process` now accepts a ``daemon`` keyword argument
1535to override the default behavior of inheriting the ``daemon`` flag from
1536the parent process (:issue:`6064`).
1537
R David Murray994ce1a2012-10-02 10:19:08 -04001538New attribute attribute :data:`multiprocessing.Process.sentinel` allows a
1539program to wait on multiple :class:`~multiprocessing.Process` objects at one
1540time using the appropriate OS primitives (for example, :mod:`select` on
1541posix systems).
1542
R David Murrayace51622012-10-06 22:26:52 -04001543New methods :meth:`multiprocessing.pool.Pool.starmap` and
1544:meth:`~multiprocessing.pool.Pool.starmap_async` provide
1545:func:`itertools.starmap` equivalents to the existing
1546:meth:`multiprocessing.pool.Pool.map` and
1547:meth:`~multiprocessing.pool.Pool.map_async` functions. (Contributed by Hynek
1548Schlawack in :issue:`12708`.)
1549
Antoine Pitrou9a864472012-05-04 23:15:47 +02001550
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001551nntplib
1552-------
1553
1554The :class:`nntplib.NNTP` class now supports the context manager protocol to
1555unconditionally consume :exc:`socket.error` exceptions and to close the NNTP
1556connection when done::
1557
1558 >>> from nntplib import NNTP
Ezio Melotti3c14b4e2011-07-13 11:44:44 +03001559 >>> with NNTP('news.gmane.org') as n:
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001560 ... n.group('gmane.comp.python.committers')
1561 ...
Ezio Melotti04f648c2011-07-26 09:37:46 +03001562 ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001563 >>>
1564
1565(Contributed by Giampaolo Rodolà in :issue:`9795`)
1566
1567
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001568os
1569--
1570
Charles-François Natalia003af12011-06-01 20:30:52 +02001571* The :mod:`os` module has a new :func:`~os.pipe2` function that makes it
1572 possible to create a pipe with :data:`~os.O_CLOEXEC` or
1573 :data:`~os.O_NONBLOCK` flags set atomically. This is especially useful to
1574 avoid race conditions in multi-threaded programs.
1575
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001576* The :mod:`os` module has a new :func:`~os.sendfile` function which provides
1577 an efficent "zero-copy" way for copying data from one file (or socket)
1578 descriptor to another. The phrase "zero-copy" refers to the fact that all of
1579 the copying of data between the two descriptors is done entirely by the
1580 kernel, with no copying of data into userspace buffers. :func:`~os.sendfile`
1581 can be used to efficiently copy data from a file on disk to a network socket,
1582 e.g. for downloading a file.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001583
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001584 (Patch submitted by Ross Lagerwall and Giampaolo Rodolà in :issue:`10882`.)
1585
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001586* To avoid race conditions like symlink attacks and issues with temporary
1587 files and directories, it is more reliable (and also faster) to manipulate
1588 file descriptors instead of file names. Python 3.3 enhances existing functions
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001589 and introduces new functions to work on file descriptors (:issue:`4761`,
Larry Hastings94717972012-09-21 09:30:19 -07001590 :issue:`10755` and :issue:`14626`).
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001591
1592 - The :mod:`os` module has a new :func:`~os.fwalk` function similar to
1593 :func:`~os.walk` except that it also yields file descriptors referring to the
1594 directories visited. This is especially useful to avoid symlink races.
1595
1596 - The following functions get new optional *dir_fd* (:ref:`paths relative to
1597 directory descriptors <dir_fd>`) and/or *follow_symlinks* (:ref:`not
1598 following symlinks <follow_symlinks>`):
1599 :func:`~os.access`, :func:`~os.chflags`, :func:`~os.chmod`, :func:`~os.chown`,
1600 :func:`~os.link`, :func:`~os.lstat`, :func:`~os.mkdir`, :func:`~os.mkfifo`,
1601 :func:`~os.mknod`, :func:`~os.open`, :func:`~os.readlink`, :func:`~os.remove`,
1602 :func:`~os.rename`, :func:`~os.replace`, :func:`~os.rmdir`, :func:`~os.stat`,
R David Murrayc652ce62012-09-30 20:07:42 -04001603 :func:`~os.symlink`, :func:`~os.unlink`, :func:`~os.utime`. Platform
1604 support for using these parameters can be checked via the sets
1605 :data:`os.supports_dir_fd` and :data:`os.supports_follows_symlinks`.
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001606
1607 - The following functions now support a file descriptor for their path argument:
1608 :func:`~os.chdir`, :func:`~os.chmod`, :func:`~os.chown`,
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001609 :func:`~os.execve`, :func:`~os.listdir`, :func:`~os.pathconf`, :func:`~os.path.exists`,
R David Murrayc652ce62012-09-30 20:07:42 -04001610 :func:`~os.stat`, :func:`~os.statvfs`, :func:`~os.utime`. Platform support
1611 for this can be checked via the :data:`os.supports_fd` set.
1612
1613* :func:`~os.access` accepts an ``effective_ids`` keyword argument to turn on
1614 using the effective uid/gid rather than the real uid/gid in the access check.
1615 Platform support for this can be checked via the
1616 :data:`~os.supports_effective_ids` set.
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001617
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001618* The :mod:`os` module has two new functions: :func:`~os.getpriority` and
1619 :func:`~os.setpriority`. They can be used to get or set process
1620 niceness/priority in a fashion similar to :func:`os.nice` but extended to all
1621 processes instead of just the current one.
1622
1623 (Patch submitted by Giampaolo Rodolà in :issue:`10784`.)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001624
Antoine Pitrou9a864472012-05-04 23:15:47 +02001625* The new :func:`os.replace` function allows cross-platform renaming of a
1626 file with overwriting the destination. With :func:`os.rename`, an existing
1627 destination file is overwritten under POSIX, but raises an error under
1628 Windows.
1629 (Contributed by Antoine Pitrou in :issue:`8828`.)
1630
Larry Hastings94717972012-09-21 09:30:19 -07001631* The stat family of functions (:func:`~os.stat`, :func:`~os.fstat`,
1632 and :func:`~os.lstat`) now support reading a file's timestamps
1633 with nanosecond precision. Symmetrically, :func:`~os.utime`
1634 can now write file timestamps with nanosecond precision. (Contributed by
1635 Larry Hastings in :issue:`14127`.)
1636
Antoine Pitrou9a864472012-05-04 23:15:47 +02001637* The new :func:`os.get_terminal_size` function queries the size of the
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001638 terminal attached to a file descriptor. See also
1639 :func:`shutil.get_terminal_size`.
Antoine Pitrou9a864472012-05-04 23:15:47 +02001640 (Contributed by Zbigniew Jędrzejewski-Szmek in :issue:`13609`.)
1641
Georg Brandldba3b5c2012-06-26 09:36:14 +02001642.. XXX sort out this mess after beta1
Victor Stinnere5064372011-10-14 00:08:29 +02001643
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001644* New functions to support Linux extended attributes (:issue:`12720`):
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001645 :func:`~os.getxattr`, :func:`~os.listxattr`, :func:`~os.removexattr`,
1646 :func:`~os.setxattr`.
Victor Stinnere5064372011-10-14 00:08:29 +02001647
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001648* New interface to the scheduler. These functions
1649 control how a process is allocated CPU time by the operating system. New
1650 functions:
1651 :func:`~os.sched_get_priority_max`, :func:`~os.sched_get_priority_min`,
1652 :func:`~os.sched_getaffinity`, :func:`~os.sched_getparam`,
1653 :func:`~os.sched_getscheduler`, :func:`~os.sched_rr_get_interval`,
1654 :func:`~os.sched_setaffinity`, :func:`~os.sched_setparam`,
1655 :func:`~os.sched_setscheduler`, :func:`~os.sched_yield`,
Victor Stinnere5064372011-10-14 00:08:29 +02001656
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001657* New functions to control the file system:
Victor Stinnere5064372011-10-14 00:08:29 +02001658
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001659 * :func:`~os.posix_fadvise`: Announces an intention to access data in a
1660 specific pattern thus allowing the kernel to make optimizations.
1661 * :func:`~os.posix_fallocate`: Ensures that enough disk space is allocated
1662 for a file.
1663 * :func:`~os.sync`: Force write of everything to disk.
Victor Stinnere5064372011-10-14 00:08:29 +02001664
R David Murrayc652ce62012-09-30 20:07:42 -04001665* Additional new posix functions:
Victor Stinnere5064372011-10-14 00:08:29 +02001666
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001667 * :func:`~os.lockf`: Apply, test or remove a POSIX lock on an open file descriptor.
1668 * :func:`~os.pread`: Read from a file descriptor at an offset, the file
1669 offset remains unchanged.
1670 * :func:`~os.pwrite`: Write to a file descriptor from an offset, leaving
1671 the file offset unchanged.
1672 * :func:`~os.readv`: Read from a file descriptor into a number of writable buffers.
1673 * :func:`~os.truncate`: Truncate the file corresponding to *path*, so that
1674 it is at most *length* bytes in size.
1675 * :func:`~os.waitid`: Wait for the completion of one or more child processes.
1676 * :func:`~os.writev`: Write the contents of *buffers* to a file descriptor,
1677 where *buffers* is an arbitrary sequence of buffers.
1678 * :func:`~os.getgrouplist` (:issue:`9344`): Return list of group ids that
1679 specified user belongs to.
Victor Stinnere5064372011-10-14 00:08:29 +02001680
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001681* :func:`~os.times` and :func:`~os.uname`: Return type changed from a tuple to
1682 a tuple-like object with named attributes.
Victor Stinnere5064372011-10-14 00:08:29 +02001683
R David Murrayc652ce62012-09-30 20:07:42 -04001684* Some platforms now support additional constants for the :func:`~os.lseek`
1685 function, such as ``os.SEEK_HOLE`` and ``os.SEEK_DATA``.
1686
R David Murray1e218c92012-10-06 18:18:55 -04001687* New constants :data:`~os.RTLD_LAZY`, :data:`~os.RTLD_NOW`,
1688 :data:`~os.RTLD_GLOBAL`, :data:`~os.RTLD_LOCAL`, :data:`~os.RTLD_NODELETE`,
1689 :data:`~os.RTLD_NOLOAD`, and :data:`~os.RTLD_DEEPBIND` are available on
1690 platforms that support them. These are for use with the
1691 :func:`sys.setdlopenflags` function, and supersede the similar constants
1692 defined in :mod:`ctypes` and :mod:`DLFCN`. (Contributed by Victor Stinner
1693 in :issue:`13226`.)
1694
R David Murrayc652ce62012-09-30 20:07:42 -04001695* :func:`os.symlink` now accepts (and ignores) the ``target_is_directory``
1696 keyword argument on non-Windows platforms, to ease cross-platform support.
1697
Giampaolo Rodolà424298a2011-03-03 18:34:06 +00001698
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001699pdb
1700---
1701
R David Murray26d15bf2012-09-29 15:13:35 -04001702Tab-completion is now available not only for command names, but also their
1703arguments. For example, for the ``break`` command, function and file names
1704are completed.
1705
1706(Contributed by Georg Brandl in :issue:`14210`)
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001707
1708
Antoine Pitrou9a864472012-05-04 23:15:47 +02001709pickle
1710------
1711
1712:class:`pickle.Pickler` objects now have an optional
1713:attr:`~pickle.Pickler.dispatch_table` attribute allowing to set per-pickler
1714reduction functions.
R David Murray26d15bf2012-09-29 15:13:35 -04001715
Antoine Pitrou9a864472012-05-04 23:15:47 +02001716(Contributed by Richard Oudkerk in :issue:`14166`.)
1717
1718
Victor Stinner383c3fc2011-05-25 01:35:05 +02001719pydoc
1720-----
1721
Victor Stinner6daa33c2011-05-25 01:41:22 +02001722The Tk GUI and the :func:`~pydoc.serve` function have been removed from the
1723:mod:`pydoc` module: ``pydoc -g`` and :func:`~pydoc.serve` have been deprecated
1724in Python 3.2.
Victor Stinner383c3fc2011-05-25 01:35:05 +02001725
1726
Antoine Pitrouad09b5d2012-06-24 22:41:33 +02001727re
1728--
1729
1730:class:`str` regular expressions now support ``\u`` and ``\U`` escapes.
1731
1732(Contributed by Serhiy Storchaka in :issue:`3665`.)
1733
1734
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001735sched
1736-----
Victor Stinner754851f2011-04-19 23:58:51 +02001737
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001738* :meth:`~sched.scheduler.run` now accepts a *blocking* parameter which when
1739 set to False makes the method execute the scheduled events due to expire
1740 soonest (if any) and then return immediately.
1741 This is useful in case you want to use the :class:`~sched.scheduler` in
1742 non-blocking applications. (Contributed by Giampaolo Rodolà in :issue:`13449`)
Victor Stinner754851f2011-04-19 23:58:51 +02001743
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001744* :class:`~sched.scheduler` class can now be safely used in multi-threaded
1745 environments. (Contributed by Josiah Carlson and Giampaolo Rodolà in
1746 :issue:`8684`)
1747
1748* *timefunc* and *delayfunct* parameters of :class:`~sched.scheduler` class
1749 constructor are now optional and defaults to :func:`time.time` and
1750 :func:`time.sleep` respectively. (Contributed by Chris Clark in
1751 :issue:`13245`)
1752
1753* :meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs`
1754 *argument* parameter is now optional. (Contributed by Chris Clark in
1755 :issue:`13245`)
1756
1757* :meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs`
1758 now accept a *kwargs* parameter. (Contributed by Chris Clark in
1759 :issue:`13245`)
1760
1761
Jesus Ceaaa264882012-10-04 02:51:22 +02001762select
1763------
1764
Jesus Ceab6bb3ad2012-10-04 02:58:48 +02001765Solaris and derivatives platforms have a new class :class:`select.devpoll`
1766for high performance asynchronous sockets via :file:`/dev/poll`.
R David Murray1e218c92012-10-06 18:18:55 -04001767(Contributed by Jesús Cea Avión in :issue:`6397`.)
Jesus Ceaaa264882012-10-04 02:51:22 +02001768
1769
R David Murrayaae25832012-09-29 09:49:05 -04001770shlex
1771-----
1772
R David Murray26d15bf2012-09-29 15:13:35 -04001773The previously undocumented helper function ``quote`` from the
1774:mod:`pipes` modules has been moved to the :mod:`shlex` module and
1775documented. :func:`~shlex.quote` properly escapes all characters in a string
1776that might be otherwise given special meaning by the shell.
R David Murrayaae25832012-09-29 09:49:05 -04001777
1778
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001779shutil
1780------
1781
R David Murrayd2489cf2012-09-30 17:28:54 -04001782* New functions:
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001783
1784 * :func:`~shutil.disk_usage`: provides total, used and free disk space
1785 statistics. (Contributed by Giampaolo Rodolà in :issue:`12442`)
1786 * :func:`~shutil.chown`: allows one to change user and/or group of the given
1787 path also specifying the user/group names and not only their numeric
1788 ids. (Contributed by Sandro Tosi in :issue:`12191`)
R David Murrayd2489cf2012-09-30 17:28:54 -04001789 * :func:`shutil.get_terminal_size`: returns the size of the terminal window
1790 to which the interpreter is attached. (Contributed by Zbigniew
1791 Jędrzejewski-Szmek in :issue:`13609`.)
Victor Stinnera9293352011-04-30 15:21:58 +02001792
Larry Hastings94717972012-09-21 09:30:19 -07001793* :func:`~shutil.copy2` and :func:`~shutil.copystat` now preserve file
1794 timestamps with nanosecond precision on platforms that support it.
1795 They also preserve file "extended attributes" on Linux. (Contributed
1796 by Larry Hastings in :issue:`14127` and :issue:`15238`.)
1797
Antoine Pitrou9a864472012-05-04 23:15:47 +02001798* Several functions now take an optional ``symlinks`` argument: when that
1799 parameter is true, symlinks aren't dereferenced and the operation instead
1800 acts on the symlink itself (or creates one, if relevant).
1801 (Contributed by Hynek Schlawack in :issue:`12715`.)
1802
R David Murrayf4c27572012-10-06 23:19:17 -04001803* When copying files to a different file system, :func:`~shutil.move` now
1804 handles symlinks the way the posix ``mv`` command does, recreating the
1805 symlink rather than copying the target file contents. (Contributed by
1806 Jonathan Niehof in :issue:`9993`.) :func:`~shutil.move` now also returns
1807 the ``dst`` argument as its result.
1808
Nick Coghlan5b0eca12012-06-24 16:43:06 +10001809* :func:`~shutil.rmtree` is now resistant to symlink attacks on platforms
1810 which support the new ``dir_fd`` parameter in :func:`os.open` and
Georg Brandldba3b5c2012-06-26 09:36:14 +02001811 :func:`os.unlink`. (Contributed by Martin von Löwis and Hynek Schlawack
Nick Coghlan5b0eca12012-06-24 16:43:06 +10001812 in :issue:`4489`.)
1813
Antoine Pitrou9a864472012-05-04 23:15:47 +02001814
Victor Stinnera9293352011-04-30 15:21:58 +02001815signal
1816------
1817
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001818* The :mod:`signal` module has new functions:
Victor Stinnera9293352011-04-30 15:21:58 +02001819
Victor Stinnerb3e72192011-05-08 01:46:11 +02001820 * :func:`~signal.pthread_sigmask`: fetch and/or change the signal mask of the
1821 calling thread (Contributed by Jean-Paul Calderone in :issue:`8407`) ;
1822 * :func:`~signal.pthread_kill`: send a signal to a thread ;
1823 * :func:`~signal.sigpending`: examine pending functions ;
1824 * :func:`~signal.sigwait`: wait a signal.
Ross Lagerwallbc808222011-06-25 12:13:40 +02001825 * :func:`~signal.sigwaitinfo`: wait for a signal, returning detailed
1826 information about it.
1827 * :func:`~signal.sigtimedwait`: like :func:`~signal.sigwaitinfo` but with a
1828 timeout.
Victor Stinnera9293352011-04-30 15:21:58 +02001829
Victor Stinnerd49b1f12011-05-08 02:03:15 +02001830* The signal handler writes the signal number as a single byte instead of
1831 a nul byte into the wakeup file descriptor. So it is possible to wait more
1832 than one signal and know which signals were raised.
1833
Victor Stinner388196e2011-05-10 17:13:00 +02001834* :func:`signal.signal` and :func:`signal.siginterrupt` raise an OSError,
1835 instead of a RuntimeError: OSError has an errno attribute.
1836
R David Murray1764c802012-09-29 11:42:36 -04001837
1838smtpd
1839-----
1840
R David Murray26d15bf2012-09-29 15:13:35 -04001841The :mod:`smtpd` module now supports :rfc:`5321` (extended SMTP) and :rfc:`1870`
1842(size extension). Per the standard, these extensions are enabled if and only
1843if the client initiates the session with an ``EHLO`` command.
R David Murray1764c802012-09-29 11:42:36 -04001844
R David Murray26d15bf2012-09-29 15:13:35 -04001845(Initial ``ELHO`` support by Alberto Trevino. Size extension by Juhana
1846Jauhiainen. Substantial additional work on the patch contributed by Michele
1847Orrù and Dan Boswell. :issue:`8739`)
R David Murray1764c802012-09-29 11:42:36 -04001848
1849
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001850smtplib
1851-------
1852
R David Murraya21e5152012-10-06 16:29:14 -04001853The :class:`~smtplib.SMTP`, :class:`~smtplib.SMTP_SSL`, and
1854:class:`~smtplib.LMTP` classes now accept a ``source_address`` keyword argument
1855to specify the ``(host, port)`` to use as the source address in the bind call
1856when creating the outgoing socket. (Contributed by Paulo Scardine in
1857:issue:`11281`.)
1858
R David Murray3430fb82012-10-02 18:24:56 -04001859:class:`~smtplib.SMTP` now supports the context manager protocol, allowing an
1860``SMTP`` instance to be used in a ``with`` statement. (Contributed
1861by Giampaolo Rodolà in :issue:`11289`.)
1862
R David Murray26d15bf2012-09-29 15:13:35 -04001863The :class:`~smtplib.SMTP_SSL` constructor and the :meth:`~smtplib.SMTP.starttls`
1864method now accept an SSLContext parameter to control parameters of the secure
R David Murray3430fb82012-10-02 18:24:56 -04001865channel. (Contributed by Kasun Herath in :issue:`8809`)
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001866
1867
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001868socket
1869------
1870
Charles-François Natali47413c12011-10-06 19:47:44 +02001871* The :class:`~socket.socket` class now exposes additional methods to process
1872 ancillary data when supported by the underlying platform:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001873
Charles-François Natali47413c12011-10-06 19:47:44 +02001874 * :func:`~socket.socket.sendmsg`
1875 * :func:`~socket.socket.recvmsg`
1876 * :func:`~socket.socket.recvmsg_into`
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001877
Charles-François Natali47413c12011-10-06 19:47:44 +02001878 (Contributed by David Watson in :issue:`6560`, based on an earlier patch by
1879 Heiko Wundram)
1880
1881* The :class:`~socket.socket` class now supports the PF_CAN protocol family
1882 (http://en.wikipedia.org/wiki/Socketcan), on Linux
1883 (http://lwn.net/Articles/253425).
1884
1885 (Contributed by Matthias Fuchs, updated by Tiago Gonçalves in :issue:`10141`)
1886
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001887* The :class:`~socket.socket` class now supports the PF_RDS protocol family
1888 (http://en.wikipedia.org/wiki/Reliable_Datagram_Sockets and
1889 http://oss.oracle.com/projects/rds/).
Victor Stinner754851f2011-04-19 23:58:51 +02001890
R David Murrayf4c27572012-10-06 23:19:17 -04001891* The :class:`~socket.socket` class now supports the ``PF_SYSTEM`` protocol
1892 family on OS X. (Contributed by Michael Goderbauer in :issue:`13777`.)
1893
R David Murrayd2489cf2012-09-30 17:28:54 -04001894* New function :func:`~socket.sethostname` allows the hostname to be set
1895 on unix systems if the calling process has sufficient privileges.
1896 (Contributed by Ross Lagerwall in :issue:`10866`.)
1897
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001898
R David Murray258fabe2012-10-01 21:43:46 -04001899socketserver
1900------------
1901
1902:class:`~socketserver.BaseServer` now has an overridable method
1903:meth:`~socketserver.BaseServer.service_actions` that is called by the
1904:meth:`~socketserver.BaseServer.serve_forever` method in the service loop.
1905:class:`~socketserver.ForkingMixIn` now uses this to clean up zombie
1906child proceses. (Contributed by Justin Warkentin in :issue:`11109`.)
1907
1908
R David Murray445d69c2012-09-30 21:59:56 -04001909sqlite3
1910-------
1911
1912New :class:`sqlite3.Connection` method
1913:meth:`~sqlite3.Connection.set_trace_callback` can be used to capture a trace of
1914all sql commands processed by sqlite. (Contributed by Torsten Landschoff
1915in :issue:`11688`.)
1916
1917
Victor Stinner99c8b162011-05-24 12:05:19 +02001918ssl
1919---
1920
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001921* The :mod:`ssl` module has two new random generation functions:
Victor Stinner99c8b162011-05-24 12:05:19 +02001922
1923 * :func:`~ssl.RAND_bytes`: generate cryptographically strong
1924 pseudo-random bytes.
1925 * :func:`~ssl.RAND_pseudo_bytes`: generate pseudo-random bytes.
1926
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001927 (Contributed by Victor Stinner in :issue:`12049`)
1928
1929* The :mod:`ssl` module now exposes a finer-grained exception hierarchy
1930 in order to make it easier to inspect the various kinds of errors.
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001931 (Contributed by Antoine Pitrou in :issue:`11183`)
1932
1933* :meth:`~ssl.SSLContext.load_cert_chain` now accepts a *password* argument
1934 to be used if the private key is encrypted.
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001935 (Contributed by Adam Simpkins in :issue:`12803`)
1936
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001937* Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is
1938 now supported through the :meth:`~ssl.SSLContext.load_dh_params` and
1939 :meth:`~ssl.SSLContext.set_ecdh_curve` methods.
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001940 (Contributed by Antoine Pitrou in :issue:`13626` and :issue:`13627`)
1941
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001942* SSL sockets have a new :meth:`~ssl.SSLSocket.get_channel_binding` method
1943 allowing the implementation of certain authentication mechanisms such as
R David Murray445d69c2012-09-30 21:59:56 -04001944 SCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny in :issue:`12551`)
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001945
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001946* You can query the SSL compression algorithm used by an SSL socket, thanks
R David Murrayfd740962012-10-06 22:08:08 -04001947 to its new :meth:`~ssl.SSLSocket.compression` method. The new attribute
1948 :attr:`~ssl.OP_NO_COMPRESSION` can be used to disable compression.
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001949 (Contributed by Antoine Pitrou in :issue:`13634`)
1950
Antoine Pitrou9a864472012-05-04 23:15:47 +02001951* Support has been added for the Next Procotol Negotiation extension using
1952 the :meth:`ssl.SSLContext.set_npn_protocols` method.
Antoine Pitrou9a864472012-05-04 23:15:47 +02001953 (Contributed by Colin Marc in :issue:`14204`)
1954
Antoine Pitrouad09b5d2012-06-24 22:41:33 +02001955* SSL errors can now be introspected more easily thanks to
1956 :attr:`~ssl.SSLError.library` and :attr:`~ssl.SSLError.reason` attributes.
Antoine Pitrouad09b5d2012-06-24 22:41:33 +02001957 (Contributed by Antoine Pitrou in :issue:`14837`)
1958
R David Murray445d69c2012-09-30 21:59:56 -04001959* The :func:`~ssl.get_server_certificate` function now supports IPv6.
1960 (Contributed by Charles-François Natali in :issue:`11811`.)
1961
R David Murrayfd740962012-10-06 22:08:08 -04001962* New attribute :attr:`~ssl.OP_CIPHER_SERVER_PREFERENCE` allows setting
1963 SSLv3 server sockets to use the server's cipher ordering preference rather
1964 than the client's (:issue:`13635`).
1965
R David Murray445d69c2012-09-30 21:59:56 -04001966
Giampaolo Rodola'ffa1d0b2012-05-15 15:30:25 +02001967stat
1968----
1969
R David Murray26d15bf2012-09-29 15:13:35 -04001970The undocumented tarfile.filemode function has been moved to
1971:func:`stat.filemode`. It can be used to convert a file's mode to a string of
1972the form '-rwxrwxrwx'.
Giampaolo Rodola'ffa1d0b2012-05-15 15:30:25 +02001973
R David Murray26d15bf2012-09-29 15:13:35 -04001974(Contributed by Giampaolo Rodolà in :issue:`14807`)
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001975
R David Murrayc652ce62012-09-30 20:07:42 -04001976
R David Murray1e218c92012-10-06 18:18:55 -04001977struct
1978------
1979
1980The :mod:`struct` module now supports ``ssize_t`` and ``size_t`` via the
1981new codes ``n`` and ``N``, respectively. (Contributed by Antoine Pitrou
1982in :issue:`3163`.)
1983
1984
R David Murrayc652ce62012-09-30 20:07:42 -04001985subprocess
1986----------
1987
1988Command strings can now be bytes objects on posix platforms. (Contributed by
R David Murray445d69c2012-09-30 21:59:56 -04001989Victor Stinner in :issue:`8513`.)
R David Murrayc652ce62012-09-30 20:07:42 -04001990
1991A new constant :data:`~subprocess.DEVNULL` allows suppressing output in a
1992platform-independent fashion. (Contributed by Ross Lagerwall in
1993:issue:`5870`.)
1994
1995
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001996sys
1997---
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +02001998
R David Murray26d15bf2012-09-29 15:13:35 -04001999The :mod:`sys` module has a new :data:`~sys.thread_info` :term:`struct
R David Murray445d69c2012-09-30 21:59:56 -04002000sequence` holding informations about the thread implementation
2001(:issue:`11223`).
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +02002002
R David Murray1e218c92012-10-06 18:18:55 -04002003
R David Murrayfd740962012-10-06 22:08:08 -04002004tarfile
2005-------
2006
2007:mod:`tarfile` now supports ``lzma`` encoding via the :mod:`lzma` module.
2008(Contributed by Lars Gustäbel in :issue:`5689`.)
2009
2010
R David Murrayca76ea12012-10-06 18:32:39 -04002011tempfile
2012--------
2013
2014:class:`tempfile.SpooledTemporaryFile`\'s
2015:meth:`~tempfile.SpooledTemporaryFile.trucate` method now accepts
2016a ``size`` parameter. (Contributed by Ryan Kelly in :issue:`9957`.)
2017
2018
Nick Coghlan4fae8cd2012-06-11 23:07:51 +10002019textwrap
2020--------
2021
R David Murray26d15bf2012-09-29 15:13:35 -04002022The :mod:`textwrap` module has a new :func:`~textwrap.indent` that makes
2023it straightforward to add a common prefix to selected lines in a block
R David Murray445d69c2012-09-30 21:59:56 -04002024of text (:issue:`13857`).
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01002025
R David Murrayd2489cf2012-09-30 17:28:54 -04002026
2027threading
2028---------
2029
R David Murrayef4d2862012-10-06 14:35:35 -04002030:class:`threading.Condition`, :class:`threading.Semaphore`,
R David Murray344174d2012-10-06 16:06:16 -04002031:class:`threading.BoundedSemaphore`, :class:`threading.Event`, and
R David Murrayef4d2862012-10-06 14:35:35 -04002032:class:`threading.Timer`, all of which used to be factory functions returning a
2033class instance, are now classes and may be subclassed. (Contributed by Éric
R David Murray344174d2012-10-06 16:06:16 -04002034Araujo in :issue:`10968`).
R David Murrayef4d2862012-10-06 14:35:35 -04002035
R David Murrayd2489cf2012-09-30 17:28:54 -04002036The :class:`threading.Thread` constructor now accepts a ``daemon`` keyword
2037argument to override the default behavior of inheriting the ``deamon`` flag
2038value from the parent thread (:issue:`6064`).
2039
R David Murray0bbfd6b2012-10-01 22:10:15 -04002040The formerly private function ``_thread.get_ident`` is now available as the
Georg Brandldc704c62012-10-02 10:16:19 +02002041public function :func:`threading.get_ident`. This eliminates several cases of
R David Murray0bbfd6b2012-10-01 22:10:15 -04002042direct access to the ``_thread`` module in the stdlib. Third party code that
2043used ``_thread.get_ident`` should likewise be changed to use the new public
2044interface.
2045
R David Murrayd2489cf2012-09-30 17:28:54 -04002046
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01002047time
2048----
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01002049
Victor Stinnerec895392012-04-29 02:41:27 +02002050The :pep:`418` added new functions to the :mod:`time` module:
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01002051
Victor Stinnerec895392012-04-29 02:41:27 +02002052* :func:`~time.get_clock_info`: Get information on a clock.
2053* :func:`~time.monotonic`: Monotonic clock (cannot go backward), not affected
2054 by system clock updates.
2055* :func:`~time.perf_counter`: Performance counter with the highest available
2056 resolution to measure a short duration.
2057* :func:`~time.process_time`: Sum of the system and user CPU time of the
2058 current process.
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01002059
Victor Stinnerec895392012-04-29 02:41:27 +02002060Other new functions:
2061
2062* :func:`~time.clock_getres`, :func:`~time.clock_gettime` and
2063 :func:`~time.clock_settime` functions with ``CLOCK_xxx`` constants.
2064 (Contributed by Victor Stinner in :issue:`10278`)
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01002065
R David Murray3430fb82012-10-02 18:24:56 -04002066To improve cross platform consistency, :func:`~time.sleep` now raises a
2067:exc:`ValueError` when passed a negative sleep value. Previously this was an
2068error on posix, but produced an infinite sleep on Windows.
2069
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01002070
Victor Stinner0db176f2012-04-16 00:16:30 +02002071types
2072-----
2073
2074Add a new :class:`types.MappingProxyType` class: Read-only proxy of a mapping.
2075(:issue:`14386`)
2076
2077
Nick Coghlan7fc570a2012-05-20 02:34:13 +10002078The new functions `types.new_class` and `types.prepare_class` provide support
2079for PEP 3115 compliant dynamic type creation. (:issue:`14588`)
2080
2081
Ezio Melotti461f41d2012-09-26 17:43:23 +03002082unittest
2083--------
2084
2085:meth:`.assertRaises`, :meth:`.assertRaisesRegex`, :meth:`.assertWarns`, and
2086:meth:`.assertWarnsRegex` now accept a keyword argument *msg* when used as
R David Murrayc652ce62012-09-30 20:07:42 -04002087context managers. (Contributed by Ezio Melotti and Winston Ewert in
2088:issue:`10775`)
Ezio Melotti461f41d2012-09-26 17:43:23 +03002089
R David Murrayc652ce62012-09-30 20:07:42 -04002090:meth:`unittest.TestCase.run` now returns the :class:`~unittest.TestResult`
2091object.
Ezio Melotti461f41d2012-09-26 17:43:23 +03002092
R David Murray1e218c92012-10-06 18:18:55 -04002093
Senthil Kumarande49d642011-10-16 23:54:44 +08002094urllib
2095------
2096
2097The :class:`~urllib.request.Request` class, now accepts a *method* argument
2098used by :meth:`~urllib.request.Request.get_method` to determine what HTTP method
Senthil Kumarana41c9422011-10-20 02:37:08 +08002099should be used. For example, this will send a ``'HEAD'`` request::
Senthil Kumarande49d642011-10-16 23:54:44 +08002100
2101 >>> urlopen(Request('http://www.python.org', method='HEAD'))
2102
2103(:issue:`1673007`)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +02002104
Giampaolo Rodola'be55d992011-11-22 13:33:34 +01002105
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002106webbrowser
2107----------
2108
R David Murrayf4c27572012-10-06 23:19:17 -04002109The :mod:`webbrowser` module supports more "browsers": Google Chrome (named
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002110:program:`chrome`, :program:`chromium`, :program:`chrome-browser` or
R David Murrayf4c27572012-10-06 23:19:17 -04002111:program:`chromium-browser` depending on the version and operating system),
2112and the generic launchers :program:`xdg-open`, from the FreeDesktop.org
2113project, and :program:`gvfs-open`, which is the default URI handler for GNOME
21143. (The former contributed by Arnaud Calmettes in :issue:`13620`, the latter
2115by Matthias Klose in :issue:`14493`)
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002116
2117
Eli Benderskyefcaba02012-08-09 08:20:20 +03002118xml.etree.ElementTree
2119---------------------
2120
2121The :mod:`xml.etree.ElementTree` module now imports its C accelerator by
2122default; there is no longer a need to explicitly import
2123:mod:`xml.etree.cElementTree` (this module stays for backwards compatibility,
2124but is now deprecated). In addition, the ``iter`` family of methods of
2125:class:`~xml.etree.ElementTree.Element` has been optimized (rewritten in C).
2126The module's documentation has also been greatly improved with added examples
2127and a more detailed reference.
2128
2129
R David Murray1e218c92012-10-06 18:18:55 -04002130zlib
2131----
2132
2133New attribute :attr:`zlib.Decompress.eof` makes it possible to distinguish
2134between a properly-formed compressed stream and an incomplete or truncated one.
2135(Contributed by Nadeem Vawda in :issue:`12646`.)
2136
2137New attribute :attr:`zlib.ZLIB_RUNTIME_VERSION` reports the version string of
2138the underlying ``zlib`` library that is loaded at runtime. (Contributed by
2139Torsten Landschoff in :issue:`12306`.)
2140
2141
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002142Optimizations
2143=============
2144
2145Major performance enhancements have been added:
2146
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002147* Thanks to :pep:`393`, some operations on Unicode strings have been optimized:
Victor Stinner46606ce2011-11-20 18:27:55 +01002148
2149 * the memory footprint is divided by 2 to 4 depending on the text
Victor Stinnera996f1e2011-11-21 13:14:43 +01002150 * encode an ASCII string to UTF-8 doesn't need to encode characters anymore,
2151 the UTF-8 representation is shared with the ASCII representation
Victor Stinner6099a032011-12-18 14:22:26 +01002152 * the UTF-8 encoder has been optimized
2153 * repeating a single ASCII letter and getting a substring of a ASCII strings
2154 is 4 times faster
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002155
Antoine Pitrou5d7e1d32012-06-24 22:38:23 +02002156* UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.
Antoine Pitrou5cec9d22012-05-17 17:37:02 +02002157
Antoine Pitrouc9092962012-06-15 22:22:18 +02002158 (contributed by Serhiy Storchaka, :issue:`14624`, :issue:`14738` and
2159 :issue:`15026`.)
Antoine Pitrou5cec9d22012-05-17 17:37:02 +02002160
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002161
2162Build and C API Changes
2163=======================
2164
2165Changes to Python's build process and to the C API include:
2166
Stefan Krah95b1ba62012-02-29 17:27:21 +01002167* New :pep:`3118` related function:
2168
2169 * :c:func:`PyMemoryView_FromMemory`
2170
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002171* :pep:`393` added new Unicode types, macros and functions:
Victor Stinner46606ce2011-11-20 18:27:55 +01002172
Victor Stinnera996f1e2011-11-21 13:14:43 +01002173 * High-level API:
2174
2175 * :c:func:`PyUnicode_CopyCharacters`
2176 * :c:func:`PyUnicode_FindChar`
2177 * :c:func:`PyUnicode_GetLength`, :c:macro:`PyUnicode_GET_LENGTH`
2178 * :c:func:`PyUnicode_New`
2179 * :c:func:`PyUnicode_Substring`
2180 * :c:func:`PyUnicode_ReadChar`, :c:func:`PyUnicode_WriteChar`
2181
2182 * Low-level API:
2183
2184 * :c:type:`Py_UCS1`, :c:type:`Py_UCS2`, :c:type:`Py_UCS4` types
2185 * :c:type:`PyASCIIObject` and :c:type:`PyCompactUnicodeObject` structures
2186 * :c:macro:`PyUnicode_READY`
2187 * :c:func:`PyUnicode_FromKindAndData`
2188 * :c:func:`PyUnicode_AsUCS4`, :c:func:`PyUnicode_AsUCS4Copy`
2189 * :c:macro:`PyUnicode_DATA`, :c:macro:`PyUnicode_1BYTE_DATA`,
2190 :c:macro:`PyUnicode_2BYTE_DATA`, :c:macro:`PyUnicode_4BYTE_DATA`
2191 * :c:macro:`PyUnicode_KIND` with :c:type:`PyUnicode_Kind` enum:
2192 :c:data:`PyUnicode_WCHAR_KIND`, :c:data:`PyUnicode_1BYTE_KIND`,
2193 :c:data:`PyUnicode_2BYTE_KIND`, :c:data:`PyUnicode_4BYTE_KIND`
2194 * :c:macro:`PyUnicode_READ`, :c:macro:`PyUnicode_READ_CHAR`, :c:macro:`PyUnicode_WRITE`
2195 * :c:macro:`PyUnicode_MAX_CHAR_VALUE`
2196
R David Murraye54c7182012-10-16 21:52:24 -04002197* :c:macro:`PyArg_ParseTuple` now accepts a :class:`bytearray` for the ``c``
2198 format (:issue:`12380`).
2199
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002200
2201
Victor Stinnerd1be8782011-12-09 00:10:41 +01002202Deprecated
2203==========
2204
Georg Brandl0cd25c92011-04-29 13:45:54 +02002205Unsupported Operating Systems
Victor Stinnerd1be8782011-12-09 00:10:41 +01002206-----------------------------
Victor Stinnerb90db4c2011-04-26 22:48:24 +02002207
Brian Curtin49a40cd2011-05-02 22:30:06 -05002208OS/2 and VMS are no longer supported due to the lack of a maintainer.
2209
2210Windows 2000 and Windows platforms which set ``COMSPEC`` to ``command.com``
2211are no longer supported due to maintenance burden.
Victor Stinnerb90db4c2011-04-26 22:48:24 +02002212
R David Murrayd2489cf2012-09-30 17:28:54 -04002213OSF support, which was deprecated in 3.2, has been completely removed.
2214
Victor Stinnerb90db4c2011-04-26 22:48:24 +02002215
Victor Stinner46606ce2011-11-20 18:27:55 +01002216Deprecated Python modules, functions and methods
Victor Stinnerd1be8782011-12-09 00:10:41 +01002217------------------------------------------------
Victor Stinner19bd0692011-11-16 00:18:57 +01002218
R David Murraye54c7182012-10-16 21:52:24 -04002219* Passing a non-empty string to ``object.__format__()`` is deprecated, and
2220 will produce a :exc:`TypeError` in Python 3.4 (:issue:`9856`).
Victor Stinner19bd0692011-11-16 00:18:57 +01002221* The ``unicode_internal`` codec has been deprecated because of the
Sandro Tosicd899122012-01-22 12:16:04 +01002222 :pep:`393`, use UTF-8, UTF-16 (``utf-16-le`` or ``utf-16-be``), or UTF-32
2223 (``utf-32-le`` or ``utf-32-be``)
Victor Stinner19bd0692011-11-16 00:18:57 +01002224* :meth:`ftplib.FTP.nlst` and :meth:`ftplib.FTP.dir`: use
Victor Stinner46606ce2011-11-20 18:27:55 +01002225 :meth:`ftplib.FTP.mlsd`
Victor Stinner19bd0692011-11-16 00:18:57 +01002226* :func:`platform.popen`: use the :mod:`subprocess` module. Check especially
R David Murrayc652ce62012-09-30 20:07:42 -04002227 the :ref:`subprocess-replacements` section (:issue:`11377`).
Victor Stinner19bd0692011-11-16 00:18:57 +01002228* :issue:`13374`: The Windows bytes API has been deprecated in the :mod:`os`
Victor Stinner46606ce2011-11-20 18:27:55 +01002229 module. Use Unicode filenames, instead of bytes filenames, to not depend on
Victor Stinner19bd0692011-11-16 00:18:57 +01002230 the ANSI code page anymore and to support any filename.
Florent Xiclunaa72a98f2012-02-13 11:03:30 +01002231* :issue:`13988`: The :mod:`xml.etree.cElementTree` module is deprecated. The
2232 accelerator is used automatically whenever available.
Victor Stinner47620a62012-04-29 02:52:39 +02002233* The behaviour of :func:`time.clock` depends on the platform: use the new
2234 :func:`time.perf_counter` or :func:`time.process_time` function instead,
2235 depending on your requirements, to have a well defined behaviour.
Victor Stinnerfa0d6282012-08-05 15:56:51 +02002236* The :func:`os.stat_float_times` function is deprecated.
Victor Stinner8f17c1c2012-08-05 16:31:32 +02002237* :mod:`abc` module:
2238
2239 * :class:`abc.abstractproperty` has been deprecated, use :class:`property`
2240 with :func:`abc.abstractmethod` instead.
2241 * :class:`abc.abstractclassmethod` has been deprecated, use
2242 :class:`classmethod` with :func:`abc.abstractmethod` instead.
2243 * :class:`abc.abstractstaticmethod` has been deprecated, use
2244 :class:`staticmethod` with :func:`abc.abstractmethod` instead.
2245
Georg Brandlfc349212012-09-26 13:11:48 +02002246* :mod:`importlib` package:
Brett Cannon288717a2012-09-25 15:23:07 -04002247
2248 * :meth:`importlib.abc.SourceLoader.path_mtime` is now deprecated in favour of
2249 :meth:`importlib.abc.SourceLoader.path_stats` as bytecode files now store
2250 both the modification time and size of the source file the bytecode file was
2251 compiled from.
2252
2253
2254
Victor Stinner19bd0692011-11-16 00:18:57 +01002255
2256
Victor Stinner46606ce2011-11-20 18:27:55 +01002257Deprecated functions and types of the C API
Victor Stinnerd1be8782011-12-09 00:10:41 +01002258-------------------------------------------
Victor Stinner46606ce2011-11-20 18:27:55 +01002259
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002260The :c:type:`Py_UNICODE` has been deprecated by :pep:`393` and will be
Victor Stinner46606ce2011-11-20 18:27:55 +01002261removed in Python 4. All functions using this type are deprecated:
2262
Victor Stinner46606ce2011-11-20 18:27:55 +01002263Unicode functions and methods using :c:type:`Py_UNICODE` and
2264:c:type:`Py_UNICODE*` types:
2265
R David Murrayf75e65f2012-09-29 15:27:53 -04002266* :c:macro:`PyUnicode_FromUnicode`: use :c:func:`PyUnicode_FromWideChar` or
2267 :c:func:`PyUnicode_FromKindAndData`
2268* :c:macro:`PyUnicode_AS_UNICODE`, :c:func:`PyUnicode_AsUnicode`,
2269 :c:func:`PyUnicode_AsUnicodeAndSize`: use :c:func:`PyUnicode_AsWideCharString`
2270* :c:macro:`PyUnicode_AS_DATA`: use :c:macro:`PyUnicode_DATA` with
2271 :c:macro:`PyUnicode_READ` and :c:macro:`PyUnicode_WRITE`
2272* :c:macro:`PyUnicode_GET_SIZE`, :c:func:`PyUnicode_GetSize`: use
2273 :c:macro:`PyUnicode_GET_LENGTH` or :c:func:`PyUnicode_GetLength`
2274* :c:macro:`PyUnicode_GET_DATA_SIZE`: use
2275 ``PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)`` (only work on ready
2276 strings)
2277* :c:func:`PyUnicode_AsUnicodeCopy`: use :c:func:`PyUnicode_AsUCS4Copy` or
2278 :c:func:`PyUnicode_AsWideCharString`
2279* :c:func:`PyUnicode_GetMax`
Victor Stinnerab595942011-12-17 04:59:06 +01002280
Victor Stinner46606ce2011-11-20 18:27:55 +01002281
Victor Stinnera996f1e2011-11-21 13:14:43 +01002282Functions and macros manipulating Py_UNICODE* strings:
2283
R David Murrayf75e65f2012-09-29 15:27:53 -04002284* :c:macro:`Py_UNICODE_strlen`: use :c:func:`PyUnicode_GetLength` or
2285 :c:macro:`PyUnicode_GET_LENGTH`
2286* :c:macro:`Py_UNICODE_strcat`: use :c:func:`PyUnicode_CopyCharacters` or
2287 :c:func:`PyUnicode_FromFormat`
2288* :c:macro:`Py_UNICODE_strcpy`, :c:macro:`Py_UNICODE_strncpy`,
2289 :c:macro:`Py_UNICODE_COPY`: use :c:func:`PyUnicode_CopyCharacters` or
2290 :c:func:`PyUnicode_Substring`
2291* :c:macro:`Py_UNICODE_strcmp`: use :c:func:`PyUnicode_Compare`
2292* :c:macro:`Py_UNICODE_strncmp`: use :c:func:`PyUnicode_Tailmatch`
2293* :c:macro:`Py_UNICODE_strchr`, :c:macro:`Py_UNICODE_strrchr`: use
2294 :c:func:`PyUnicode_FindChar`
2295* :c:macro:`Py_UNICODE_FILL`: use :c:func:`PyUnicode_Fill`
2296* :c:macro:`Py_UNICODE_MATCH`
Victor Stinnera996f1e2011-11-21 13:14:43 +01002297
Victor Stinner46606ce2011-11-20 18:27:55 +01002298Encoders:
2299
R David Murrayf75e65f2012-09-29 15:27:53 -04002300* :c:func:`PyUnicode_Encode`: use :c:func:`PyUnicode_AsEncodedObject`
2301* :c:func:`PyUnicode_EncodeUTF7`
2302* :c:func:`PyUnicode_EncodeUTF8`: use :c:func:`PyUnicode_AsUTF8` or
2303 :c:func:`PyUnicode_AsUTF8String`
2304* :c:func:`PyUnicode_EncodeUTF32`
2305* :c:func:`PyUnicode_EncodeUTF16`
2306* :c:func:`PyUnicode_EncodeUnicodeEscape:` use
2307 :c:func:`PyUnicode_AsUnicodeEscapeString`
2308* :c:func:`PyUnicode_EncodeRawUnicodeEscape:` use
2309 :c:func:`PyUnicode_AsRawUnicodeEscapeString`
2310* :c:func:`PyUnicode_EncodeLatin1`: use :c:func:`PyUnicode_AsLatin1String`
2311* :c:func:`PyUnicode_EncodeASCII`: use :c:func:`PyUnicode_AsASCIIString`
2312* :c:func:`PyUnicode_EncodeCharmap`
2313* :c:func:`PyUnicode_TranslateCharmap`
2314* :c:func:`PyUnicode_EncodeMBCS`: use :c:func:`PyUnicode_AsMBCSString` or
2315 :c:func:`PyUnicode_EncodeCodePage` (with ``CP_ACP`` code_page)
2316* :c:func:`PyUnicode_EncodeDecimal`,
2317 :c:func:`PyUnicode_TransformDecimalToASCII`
Victor Stinner46606ce2011-11-20 18:27:55 +01002318
2319
Stefan Krah029780b2012-08-24 20:14:12 +02002320Deprecated features
2321-------------------
2322
2323The :mod:`array` module's ``'u'`` format code is now deprecated and will be
2324removed in Python 4 together with the rest of the (:c:type:`Py_UNICODE`) API.
2325
2326
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002327Porting to Python 3.3
2328=====================
2329
2330This section lists previously described changes and other bugfixes
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002331that may require changes to your code.
2332
Barry Warsawc1e721b2012-07-30 16:24:12 -04002333.. _portingpythoncode:
2334
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002335Porting Python code
2336-------------------
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00002337
Victor Stinnerfa0d6282012-08-05 15:56:51 +02002338* Hash randomization is enabled by default. Set the :envvar:`PYTHONHASHSEED`
2339 environment variable to ``0`` to disable hash randomization. See also the
2340 :meth:`object.__hash__` method.
Georg Brandld6c43402012-03-07 08:55:52 +01002341
Victor Stinner19bd0692011-11-16 00:18:57 +01002342* :issue:`12326`: On Linux, sys.platform doesn't contain the major version
Victor Stinnerff3d9392011-08-20 23:39:26 +02002343 anymore. It is now always 'linux', instead of 'linux2' or 'linux3' depending
2344 on the Linux version used to build Python. Replace sys.platform == 'linux2'
2345 with sys.platform.startswith('linux'), or directly sys.platform == 'linux' if
2346 you don't need to support older Python versions.
Éric Araujoc09fca62011-03-23 02:06:24 +01002347
Victor Stinnerecc6e662012-03-14 00:39:29 +01002348* :issue:`13847`, :issue:`14180`: :mod:`time` and :mod:`datetime`:
2349 :exc:`OverflowError` is now raised instead of :exc:`ValueError` if a
2350 timestamp is out of range. :exc:`OSError` is now raised if C functions
2351 :c:func:`gmtime` or :c:func:`localtime` failed.
2352
Brett Cannonc2043482012-04-29 20:59:41 -04002353* The default finders used by import now utilize a cache of what is contained
2354 within a specific directory. If you create a Python source file or sourceless
2355 bytecode file, make sure to call :func:`importlib.invalidate_caches` to clear
2356 out the cache for the finders to notice the new file.
2357
2358* :exc:`ImportError` now uses the full name of the module that was attemped to
2359 be imported. Doctests that check ImportErrors' message will need to be
2360 updated to use the full name of the module instead of just the tail of the
2361 name.
2362
Ezio Melotti7598e182012-09-20 08:33:53 +03002363* The *index* argument to :func:`__import__` now defaults to 0 instead of -1
Brett Cannonc2043482012-04-29 20:59:41 -04002364 and no longer support negative values. It was an oversight when :pep:`328` was
2365 implemented that the default value remained -1. If you need to continue to
2366 perform a relative import followed by an absolute import, then perform the
2367 relative import using an index of 1, followed by another import using an
2368 index of 0. It is preferred, though, that you use
2369 :func:`importlib.import_module` rather than call :func:`__import__` directly.
2370
2371* :func:`__import__` no longer allows one to use an index value other than 0
2372 for top-level modules. E.g. ``__import__('sys', level=1)`` is now an error.
2373
2374* Because :attr:`sys.meta_path` and :attr:`sys.path_hooks` now have finders on
2375 them by default, you will most likely want to use :meth:`list.insert` instead
2376 of :meth:`list.append` to add to those lists.
2377
2378* Because ``None`` is now inserted into :attr:`sys.path_importer_cache`, if you
2379 are clearing out entries in the dictionary of paths that do not have a
2380 finder, you will need to remove keys paired with values of ``None`` **and**
Brett Cannon903c27c2012-07-09 14:15:32 -04002381 :class:`imp.NullImporter` to be backwards-compatible. This will lead to extra
Brett Cannonc2043482012-04-29 20:59:41 -04002382 overhead on older versions of Python that re-insert ``None`` into
2383 :attr:`sys.path_importer_cache` where it repesents the use of implicit
2384 finders, but semantically it should not change anything.
2385
Brett Cannon077ef452012-08-02 17:50:06 -04002386* :class:`importlib.abc.Finder` no longer specifies a `find_module()` abstract
2387 method that must be implemented. If you were relying on subclasses to
2388 implement that method, make sure to check for the method's existence first.
2389 You will probably want to check for `find_loader()` first, though, in the
2390 case of working with :term:`path entry finders <path entry finder>`.
2391
Nick Coghlan60610002012-07-15 22:39:39 +10002392* :mod:`pkgutil` has been converted to use :mod:`importlib` internally. This
2393 eliminates many edge cases where the old behaviour of the PEP 302 import
2394 emulation failed to match the behaviour of the real import system. The
2395 import emulation itself is still present, but is now deprecated. The
2396 :func:`pkgutil.iter_importers` and :func:`pkgutil.walk_packages` functions
2397 special case the standard import hooks so they are still supported even
2398 though they do not provide the non-standard ``iter_modules()`` method.
Brett Cannon903c27c2012-07-09 14:15:32 -04002399
R David Murrayea226852012-09-30 01:27:24 -04002400* A longstanding RFC-compliance bug (:issue:`1079`) in the parsing done by
2401 :func:`email.header.decode_header` has been fixed. Code that uses the
2402 standard idiom to convert encoded headers into unicode
2403 (``str(make_header(decode_header(h))``) will see no change, but code that
2404 looks at the individual tuples returned by decode_header will see that
2405 whitespace that precedes or follows ``ASCII`` sections is now included in the
2406 ``ASCII`` section. Code that builds headers using ``make_header`` should
2407 also continue to work without change, since ``make_header`` continues to add
2408 whitespace between ``ASCII`` and non-``ASCII`` sections if it is not already
2409 present in the input strings.
2410
2411* :func:`email.utils.formataddr` now does the correct content transfer
2412 encoding when passed non-``ASCII`` display names. Any code that depended on
2413 the previous buggy behavior that preserved the non-``ASCII`` unicode in the
R David Murrayd2489cf2012-09-30 17:28:54 -04002414 formatted output string will need to be changed (:issue:`1690608`).
2415
2416* :meth:`poplib.POP3.quit` may now raise protocol errors like all other
2417 ``poplib`` methods. Code that assumes ``quit`` does not raise
2418 :exc:`poplib.error_proto` errors may need to be changed if errors on ``quit``
2419 are encountered by a particular application (:issue:`11291`).
R David Murrayea226852012-09-30 01:27:24 -04002420
R David Murray445d69c2012-09-30 21:59:56 -04002421* The ``strict`` argument to :class:`email.parser.Parser`, deprecated since
2422 Python 2.4, has finally been removed.
2423
2424* The deprecated method ``unittest.TestCase.assertSameElements`` has been
2425 removed.
2426
2427* The deprecated variable ``time.accept2dyear`` has been removed.
2428
R David Murray1e218c92012-10-06 18:18:55 -04002429* The deprecated ``Context._clamp`` attribute has been removed from the
2430 :mod:`decimal` module. It was previously replaced by the public attribute
2431 :attr:`~decimal.Context.clamp`. (See :issue:`8540`.)
2432
R David Murray3430fb82012-10-02 18:24:56 -04002433* The undocumented internal helper class ``SSLFakeFile`` has been removed
2434 from :mod:`smtplib`, since its functionality has long been provided directly
2435 by :meth:`socket.socket.makefile`.
2436
2437* Passing a negative value to :func:`time.sleep` on Windows now raises an
2438 error instead of sleeping forever. It has always raised an error on posix.
2439
2440* The ``ast.__version__`` constant has been removed. If you need to
2441 make decisions affected by the AST version, use :attr:`sys.version_info`
2442 to make the decision.
R David Murray994ce1a2012-10-02 10:19:08 -04002443
R David Murrayef4d2862012-10-06 14:35:35 -04002444* Code that used to work around the fact that the :mod:`threading` module used
2445 factory functions by subclassing the private classes will need to change to
2446 subclass the now-public classes.
2447
R David Murraye54c7182012-10-16 21:52:24 -04002448* The undocumented debugging machinery in the threading module has been
2449 removed, simplifying the code. This should have no effect on production
2450 code, but is mentioned here in case any application debug frameworks were
2451 interacting with it (:issue:`13550`).
2452
Brett Cannonc2043482012-04-29 20:59:41 -04002453
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002454Porting C code
2455--------------
2456
Stefan Krah54c32032012-02-29 17:47:21 +01002457* In the course of changes to the buffer API the undocumented
2458 :c:member:`~Py_buffer.smalltable` member of the
2459 :c:type:`Py_buffer` structure has been removed and the
2460 layout of the :c:type:`PyMemoryViewObject` has changed.
2461
2462 All extensions relying on the relevant parts in ``memoryobject.h``
2463 or ``object.h`` must be rebuilt.
2464
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002465* Due to :ref:`PEP 393 <pep-393>`, the :c:type:`Py_UNICODE` type and all
2466 functions using this type are deprecated (but will stay available for
2467 at least five years). If you were using low-level Unicode APIs to
2468 construct and access unicode objects and you want to benefit of the
Éric Araujo4f61a2d2012-04-04 23:01:01 -04002469 memory footprint reduction provided by PEP 393, you have to convert
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002470 your code to the new :doc:`Unicode API <../c-api/unicode>`.
2471
2472 However, if you only have been using high-level functions such as
2473 :c:func:`PyUnicode_Concat()`, :c:func:`PyUnicode_Join` or
2474 :c:func:`PyUnicode_FromFormat()`, your code will automatically take
2475 advantage of the new unicode representations.
2476
Brett Cannon77b2abd2012-07-09 16:09:00 -04002477* :c:func:`PyImport_GetMagicNumber` now returns -1 upon failure.
2478
Ezio Melotti7598e182012-09-20 08:33:53 +03002479* As a negative value for the *level* argument to :func:`__import__` is no
Brett Cannon522267e2012-08-10 18:55:08 -04002480 longer valid, the same now holds for :c:func:`PyImport_ImportModuleLevel`.
Ezio Melotti7598e182012-09-20 08:33:53 +03002481 This also means that the value of *level* used by
Brett Cannon522267e2012-08-10 18:55:08 -04002482 :c:func:`PyImport_ImportModuleEx` is now 0 instead of -1.
2483
Brett Cannon77b2abd2012-07-09 16:09:00 -04002484
Antoine Pitrouc229e6e2012-02-20 19:41:11 +01002485Building C extensions
2486---------------------
2487
2488* The range of possible file names for C extensions has been narrowed.
2489 Very rarely used spellings have been suppressed: under POSIX, files
2490 named ``xxxmodule.so``, ``xxxmodule.abi3.so`` and
2491 ``xxxmodule.cpython-*.so`` are no longer recognized as implementing
2492 the ``xxx`` module. If you had been generating such files, you have
2493 to switch to the other spellings (i.e., remove the ``module`` string
2494 from the file names).
2495
2496 (implemented in :issue:`14040`.)
2497
2498
R David Murray1764c802012-09-29 11:42:36 -04002499Command Line Switch Changes
2500---------------------------
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02002501
R David Murray1764c802012-09-29 11:42:36 -04002502* The -Q command-line flag and related artifacts have been removed. Code
2503 checking sys.flags.division_warning will need updating.
Éric Araujobe3bd572011-03-26 01:55:15 +01002504
R David Murray1764c802012-09-29 11:42:36 -04002505 (:issue:`10998`, contributed by Éric Araujo.)
2506
2507* When :program:`python` is started with :option:`-S`, ``import site``
2508 will no longer add site-specific paths to the module search paths. In
2509 previous versions, it did.
2510
2511 (:issue:`11591`, contributed by Carl Meyer with editions by Éric Araujo.)