blob: f7a928adae5b3adc670f59553489afb442f6484c [file] [log] [blame]
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001****************************
2 What's New In Python 3.3
3****************************
4
5:Author: Raymond Hettinger
6:Release: |release|
7:Date: |today|
8
Éric Araujob07b97f2011-10-05 01:03:34 +02009.. Rules for maintenance:
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000010
11 * Anyone can add text to this document. Do not spend very much time
12 on the wording of your changes, because your text will probably
13 get rewritten to some degree.
14
15 * The maintainer will go through Misc/NEWS periodically and add
16 changes; it's therefore more important to add your changes to
17 Misc/NEWS than to this file.
18
19 * This is not a complete list of every single change; completeness
20 is the purpose of Misc/NEWS. Some changes I consider too small
21 or esoteric to include. If such a change is added to the text,
22 I'll just remove it. (This is another reason you shouldn't spend
23 too much time on writing your addition.)
24
25 * If you want to draw your new text to the attention of the
26 maintainer, add 'XXX' to the beginning of the paragraph or
27 section.
28
29 * It's OK to just add a fragmentary note about a change. For
30 example: "XXX Describe the transmogrify() function added to the
31 socket module." The maintainer will research the change and
32 write the necessary text.
33
34 * You can comment out your additions if you like, but it's not
35 necessary (especially when a final release is some months away).
36
37 * Credit the author of a patch or bugfix. Just the name is
38 sufficient; the e-mail address isn't necessary.
39
40 * It's helpful to add the bug/patch number as a comment:
41
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000042 XXX Describe the transmogrify() function added to the socket
43 module.
Éric Araujob07b97f2011-10-05 01:03:34 +020044 (Contributed by P.Y. Developer in :issue:`12345`.)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000045
Éric Araujob07b97f2011-10-05 01:03:34 +020046 This saves the maintainer the effort of going through the Mercurial log
Giampaolo Rodolà3108f982011-02-24 20:59:48 +000047 when researching a change.
48
49This article explains the new features in Python 3.3, compared to 3.2.
50
Georg Brandl988049a2012-06-24 18:12:24 +020051.. note:: Beta users should be aware that this document is currently in
Nick Coghlanb47b5392012-05-26 01:31:25 +100052 draft form. It will be updated substantially as Python 3.3 moves towards
53 release, so it's worth checking back even after reading earlier versions.
54
55
Antoine Pitrouc907de92012-08-21 00:53:06 +020056Summary -- Release highlights
57=============================
Victor Stinner636130e2012-08-05 16:37:12 +020058
Antoine Pitrouc907de92012-08-21 00:53:06 +020059.. This section singles out the most important changes in Python 3.3.
60 Brevity is key.
Victor Stinner636130e2012-08-05 16:37:12 +020061
Antoine Pitrouc907de92012-08-21 00:53:06 +020062New syntax features:
Victor Stinner636130e2012-08-05 16:37:12 +020063
Antoine Pitrouc907de92012-08-21 00:53:06 +020064* New ``yield from`` expression for :ref:`generator delegation <pep-380>`.
65* The ``u'unicode'`` syntax is accepted again for :class:`str` objects.
Victor Stinner636130e2012-08-05 16:37:12 +020066
Antoine Pitrouc907de92012-08-21 00:53:06 +020067New library modules:
68
69* :mod:`faulthandler` (helps debugging low-level crashes)
70* :mod:`ipaddress` (high-level objects representing IP addresses and masks)
71* :mod:`lzma` (compress data using the XZ / LZMA algorithm)
72* :mod:`venv` (Python :ref:`virtual environments <pep-405>`, as in the
73 popular ``virtualenv`` package)
74
75New built-in features:
76
77* Reworked :ref:`I/O exception hierarchy <pep-3151>`.
78
79Implementation improvements:
80
81* Rewritten :ref:`import machinery <importlib>` based on :mod:`importlib`.
82* More compact :ref:`unicode strings <pep-393>`.
83* More compact :ref:`attribute dictionaries <pep-412>`.
84
85Security improvements:
86
87* Hash randomization is switched on by default.
88
89Please read on for a comprehensive list of user-facing changes.
90
91
92.. _pep-405:
Victor Stinner636130e2012-08-05 16:37:12 +020093
Éric Araujo859aad62012-06-24 00:07:41 -040094PEP 405: Virtual Environments
95=============================
Nick Coghlanb47b5392012-05-26 01:31:25 +100096
Éric Araujo859aad62012-06-24 00:07:41 -040097- inspired by ``virtualenv``, a tool widely used by the community
98- change to the interpreter to avoid hacks
Nick Coghlanb47b5392012-05-26 01:31:25 +100099
Éric Araujo859aad62012-06-24 00:07:41 -0400100The :mod:`venv` module and ``pyvenv`` script (inspired by ``virtualenv``, a
101tool widely used by the community).
102
103.. also mention the interpreter changes that avoid the hacks used in virtualenv
Nick Coghlanb47b5392012-05-26 01:31:25 +1000104
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000105
Éric Araujo859aad62012-06-24 00:07:41 -0400106PEP 420: Namespace Packages
107===========================
108
109Native support for package directories that don't require ``__init__.py``
110marker files and can automatically span multiple path segments (inspired by
111various third party approaches to namespace packages, as described in
112:pep:`420`)
113
114
115.. _pep-3118-update:
Nick Coghlan98e20702012-03-06 21:50:13 +1000116
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100117PEP 3118: New memoryview implementation and buffer protocol documentation
118=========================================================================
119
120:issue:`10181` - memoryview bug fixes and features.
121 Written by Stefan Krah.
122
123The new memoryview implementation comprehensively fixes all ownership and
124lifetime issues of dynamically allocated fields in the Py_buffer struct
125that led to multiple crash reports. Additionally, several functions that
126crashed or returned incorrect results for non-contiguous or multi-dimensional
127input have been fixed.
128
129The memoryview object now has a PEP-3118 compliant getbufferproc()
130that checks the consumer's request type. Many new features have been
131added, most of them work in full generality for non-contiguous arrays
132and arrays with suboffsets.
133
134The documentation has been updated, clearly spelling out responsibilities
135for both exporters and consumers. Buffer request flags are grouped into
136basic and compound flags. The memory layout of non-contiguous and
137multi-dimensional NumPy-style arrays is explained.
138
139Features
140--------
141
142* All native single character format specifiers in struct module syntax
143 (optionally prefixed with '@') are now supported.
144
145* With some restrictions, the cast() method allows changing of format and
146 shape of C-contiguous arrays.
147
148* Multi-dimensional list representations are supported for any array type.
149
150* Multi-dimensional comparisons are supported for any array type.
151
152* All array types are hashable if the exporting object is hashable
Nick Coghlan98e20702012-03-06 21:50:13 +1000153 and the view is read-only. (Contributed by Antoine Pitrou in
154 :issue:`13411`)
155
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100156
157* Arbitrary slicing of any 1-D arrays type is supported. For example, it
158 is now possible to reverse a memoryview in O(1) by using a negative step.
159
160API changes
161-----------
162
163* The maximum number of dimensions is officially limited to 64.
164
165* The representation of empty shape, strides and suboffsets is now
166 an empty tuple instead of None.
167
168* Accessing a memoryview element with format 'B' (unsigned bytes)
169 now returns an integer (in accordance with the struct module syntax).
170 For returning a bytes object the view must be cast to 'c' first.
171
Stefan Krah54c32032012-02-29 17:47:21 +0100172* For further changes see `Build and C API Changes`_ and `Porting C code`_ .
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100173
Antoine Pitrou037ffbf2011-10-24 00:25:41 +0200174.. _pep-393:
175
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300176PEP 393: Flexible String Representation
177=======================================
178
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200179The Unicode string type is changed to support multiple internal
180representations, depending on the character with the largest Unicode ordinal
181(1, 2, or 4 bytes) in the represented string. This allows a space-efficient
182representation in common cases, but gives access to full UCS-4 on all
183systems. For compatibility with existing APIs, several representations may
184exist in parallel; over time, this compatibility should be phased out.
Ezio Melotti397546a2011-09-29 08:34:36 +0300185
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200186On the Python side, there should be no downside to this change.
Ezio Melotti397546a2011-09-29 08:34:36 +0300187
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200188On the C API side, PEP 393 is fully backward compatible. The legacy API
189should remain available at least five years. Applications using the legacy
190API will not fully benefit of the memory reduction, or - worse - may use
191a bit more memory, because Python may have to maintain two versions of each
192string (in the legacy format and in the new efficient storage).
193
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100194Functionality
195-------------
196
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200197Changes introduced by :pep:`393` are the following:
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300198
Ezio Melotti397546a2011-09-29 08:34:36 +0300199* Python now always supports the full range of Unicode codepoints, including
200 non-BMP ones (i.e. from ``U+0000`` to ``U+10FFFF``). The distinction between
201 narrow and wide builds no longer exists and Python now behaves like a wide
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200202 build, even under Windows.
Ezio Melotti397546a2011-09-29 08:34:36 +0300203
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200204* With the death of narrow builds, the problems specific to narrow builds have
205 also been fixed, for example:
Ezio Melotti397546a2011-09-29 08:34:36 +0300206
207 * :func:`len` now always returns 1 for non-BMP characters,
208 so ``len('\U0010FFFF') == 1``;
209
210 * surrogate pairs are not recombined in string literals,
211 so ``'\uDBFF\uDFFF' != '\U0010FFFF'``;
212
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200213 * indexing or slicing non-BMP characters returns the expected value,
Ezio Melotti397546a2011-09-29 08:34:36 +0300214 so ``'\U0010FFFF'[0]`` now returns ``'\U0010FFFF'`` and not ``'\uDBFF'``;
215
Antoine Pitroud136aec2011-11-17 01:48:06 +0100216 * all other functions in the standard library now correctly handle
Antoine Pitroufd9b4162011-10-24 00:14:43 +0200217 non-BMP codepoints.
Ezio Melotti397546a2011-09-29 08:34:36 +0300218
Ezio Melotti48a2f8f2011-09-29 00:18:19 +0300219* The value of :data:`sys.maxunicode` is now always ``1114111`` (``0x10FFFF``
220 in hexadecimal). The :c:func:`PyUnicode_GetMax` function still returns
221 either ``0xFFFF`` or ``0x10FFFF`` for backward compatibility, and it should
222 not be used with the new Unicode API (see :issue:`13054`).
223
Ezio Melotti397546a2011-09-29 08:34:36 +0300224* The :file:`./configure` flag ``--with-wide-unicode`` has been removed.
Victor Stinner7d637ab2011-09-29 02:56:16 +0200225
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100226Performance and resource usage
227------------------------------
228
229The storage of Unicode strings now depends on the highest codepoint in the string:
230
231* pure ASCII and Latin1 strings (``U+0000-U+00FF``) use 1 byte per codepoint;
232
233* BMP strings (``U+0000-U+FFFF``) use 2 bytes per codepoint;
234
235* non-BMP strings (``U+10000-U+10FFFF``) use 4 bytes per codepoint.
236
Martin v. Löwisde157cc2012-03-06 08:42:17 +0100237The net effect is that for most applications, memory usage of string
238storage should decrease significantly - especially compared to former
239wide unicode builds - as, in many cases, strings will be pure ASCII
240even in international contexts (because many strings store non-human
241language data, such as XML fragments, HTTP headers, JSON-encoded data,
242etc.). We also hope that it will, for the same reasons, increase CPU
243cache efficiency on non-trivial applications. The memory usage of
244Python 3.3 is two to three times smaller than Python 3.2, and a little
245bit better than Python 2.7, on a Django benchmark (see the PEP for
246details).
Antoine Pitrou0599b5b2011-11-29 22:45:07 +0100247
Éric Araujob07b97f2011-10-05 01:03:34 +0200248
Antoine Pitrouc907de92012-08-21 00:53:06 +0200249.. _pep-3151:
250
Victor Stinnera1bf2982011-10-12 20:35:02 +0200251PEP 3151: Reworking the OS and IO exception hierarchy
252=====================================================
253
254:pep:`3151` - Reworking the OS and IO exception hierarchy
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200255 PEP written and implemented by Antoine Pitrou.
Victor Stinnera1bf2982011-10-12 20:35:02 +0200256
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200257The hierarchy of exceptions raised by operating system errors is now both
258simplified and finer-grained.
Victor Stinnera1bf2982011-10-12 20:35:02 +0200259
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200260You don't have to worry anymore about choosing the appropriate exception
261type between :exc:`OSError`, :exc:`IOError`, :exc:`EnvironmentError`,
262:exc:`WindowsError`, :exc:`mmap.error`, :exc:`socket.error` or
263:exc:`select.error`. All these exception types are now only one:
264:exc:`OSError`. The other names are kept as aliases for compatibility
265reasons.
Victor Stinnera1bf2982011-10-12 20:35:02 +0200266
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200267Also, it is now easier to catch a specific error condition. Instead of
268inspecting the ``errno`` attribute (or ``args[0]``) for a particular
269constant from the :mod:`errno` module, you can catch the adequate
270:exc:`OSError` subclass. The available subclasses are the following:
Victor Stinnera1bf2982011-10-12 20:35:02 +0200271
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200272* :exc:`BlockingIOError`
273* :exc:`ChildProcessError`
274* :exc:`ConnectionError`
275* :exc:`FileExistsError`
276* :exc:`FileNotFoundError`
277* :exc:`InterruptedError`
278* :exc:`IsADirectoryError`
279* :exc:`NotADirectoryError`
280* :exc:`PermissionError`
281* :exc:`ProcessLookupError`
282* :exc:`TimeoutError`
Victor Stinnera1bf2982011-10-12 20:35:02 +0200283
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200284And the :exc:`ConnectionError` itself has finer-grained subclasses:
Victor Stinnera1bf2982011-10-12 20:35:02 +0200285
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200286* :exc:`BrokenPipeError`
287* :exc:`ConnectionAbortedError`
288* :exc:`ConnectionRefusedError`
289* :exc:`ConnectionResetError`
Victor Stinnera1bf2982011-10-12 20:35:02 +0200290
291Thanks to the new exceptions, common usages of the :mod:`errno` can now be
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200292avoided. For example, the following code written for Python 3.2::
Victor Stinnera1bf2982011-10-12 20:35:02 +0200293
294 from errno import ENOENT, EACCES, EPERM
295
296 try:
297 with open("document.txt") as f:
298 content = f.read()
299 except IOError as err:
300 if err.errno == ENOENT:
301 print("document.txt file is missing")
302 elif err.errno in (EACCES, EPERM):
303 print("You are not allowed to read document.txt")
304 else:
305 raise
306
Antoine Pitrou01fd26c2011-10-24 00:07:02 +0200307can now be written without the :mod:`errno` import and without manual
308inspection of exception attributes::
Victor Stinnera1bf2982011-10-12 20:35:02 +0200309
310 try:
311 with open("document.txt") as f:
312 content = f.read()
313 except FileNotFoundError:
314 print("document.txt file is missing")
315 except PermissionError:
316 print("You are not allowed to read document.txt")
317
318
Antoine Pitrouc907de92012-08-21 00:53:06 +0200319.. _pep-380:
320
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000321PEP 380: Syntax for Delegating to a Subgenerator
322================================================
323
Nick Coghlanab7bf212012-02-26 17:49:52 +1000324:pep:`380` - Syntax for Delegating to a Subgenerator
325 PEP written by Greg Ewing.
326
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000327PEP 380 adds the ``yield from`` expression, allowing a generator to delegate
328part of its operations to another generator. This allows a section of code
329containing 'yield' to be factored out and placed in another generator.
330Additionally, the subgenerator is allowed to return with a value, and the
331value is made available to the delegating generator.
Nick Coghlanb9b281b2012-03-06 22:31:12 +1000332
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000333While designed primarily for use in delegating to a subgenerator, the ``yield
334from`` expression actually allows delegation to arbitrary subiterators.
335
Nick Coghlanb9b281b2012-03-06 22:31:12 +1000336For simple iterators, ``yield from iterable`` is essentially just a shortened
337form of ``for item in iterable: yield item``::
338
339 >>> def g(x):
340 ... yield from range(x, 0, -1)
341 ... yield from range(x)
342 ...
343 >>> list(g(5))
344 [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
345
346However, unlike an ordinary loop, ``yield from`` allows subgenerators to
347receive sent and thrown values directly from the calling scope, and
348return a final value to the outer generator::
349
350 >>> def accumulate(start=0):
351 ... tally = start
352 ... while 1:
353 ... next = yield
354 ... if next is None:
355 ... return tally
356 ... tally += next
357 ...
358 >>> def gather_tallies(tallies, start=0):
359 ... while 1:
360 ... tally = yield from accumulate()
361 ... tallies.append(tally)
362 ...
363 >>> tallies = []
364 >>> acc = gather_tallies(tallies)
365 >>> next(acc) # Ensure the accumulator is ready to accept values
366 >>> for i in range(10):
367 ... acc.send(i)
368 ...
369 >>> acc.send(None) # Finish the first tally
370 >>> for i in range(5):
371 ... acc.send(i)
372 ...
373 >>> acc.send(None) # Finish the second tally
374 >>> tallies
375 [45, 10]
376
377The main principle driving this change is to allow even generators that are
378designed to be used with the ``send`` and ``throw`` methods to be split into
379multiple subgenerators as easily as a single large function can be split into
380multiple subfunctions.
381
Nick Coghlan1f7ce622012-01-13 21:43:40 +1000382(Implementation by Greg Ewing, integrated into 3.3 by Renaud Blanch, Ryan
383Kelly and Nick Coghlan, documentation by Zbigniew Jędrzejewski-Szmek and
384Nick Coghlan)
385
386
Nick Coghlanab7bf212012-02-26 17:49:52 +1000387PEP 409: Suppressing exception context
388======================================
389
390:pep:`409` - Suppressing exception context
391 PEP written by Ethan Furman, implemented by Ethan Furman and Nick Coghlan.
392
393PEP 409 introduces new syntax that allows the display of the chained
394exception context to be disabled. This allows cleaner error messages in
395applications that convert between exception types::
396
397 >>> class D:
398 ... def __init__(self, extra):
399 ... self._extra_attributes = extra
400 ... def __getattr__(self, attr):
401 ... try:
402 ... return self._extra_attributes[attr]
403 ... except KeyError:
404 ... raise AttributeError(attr) from None
405 ...
406 >>> D({}).x
407 Traceback (most recent call last):
408 File "<stdin>", line 1, in <module>
409 File "<stdin>", line 8, in __getattr__
410 AttributeError: x
411
412Without the ``from None`` suffix to suppress the cause, the original
413exception would be displayed by default::
414
415 >>> class C:
416 ... def __init__(self, extra):
417 ... self._extra_attributes = extra
418 ... def __getattr__(self, attr):
419 ... try:
420 ... return self._extra_attributes[attr]
421 ... except KeyError:
422 ... raise AttributeError(attr)
423 ...
424 >>> C({}).x
425 Traceback (most recent call last):
426 File "<stdin>", line 6, in __getattr__
427 KeyError: 'x'
428
429 During handling of the above exception, another exception occurred:
430
431 Traceback (most recent call last):
432 File "<stdin>", line 1, in <module>
433 File "<stdin>", line 8, in __getattr__
434 AttributeError: x
435
436No debugging capability is lost, as the original exception context remains
437available if needed (for example, if an intervening library has incorrectly
438suppressed valuable underlying details)::
439
440 >>> try:
441 ... D({}).x
442 ... except AttributeError as exc:
443 ... print(repr(exc.__context__))
444 ...
445 KeyError('x',)
446
447
Nick Coghlan98e20702012-03-06 21:50:13 +1000448PEP 414: Explicit Unicode literals
449======================================
450
451:pep:`414` - Explicit Unicode literals
452 PEP written by Armin Ronacher.
453
454To ease the transition from Python 2 for Unicode aware Python applications
455that make heavy use of Unicode literals, Python 3.3 once again supports the
456"``u``" prefix for string literals. This prefix has no semantic significance
457in Python 3, it is provided solely to reduce the number of purely mechanical
458changes in migrating to Python 3, making it easier for developers to focus on
459the more significant semantic changes (such as the stricter default
460separation of binary and text data).
461
462
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100463PEP 3155: Qualified name for classes and functions
464==================================================
465
466:pep:`3155` - Qualified name for classes and functions
467 PEP written and implemented by Antoine Pitrou.
468
469Functions and class objects have a new ``__qualname__`` attribute representing
470the "path" from the module top-level to their definition. For global functions
471and classes, this is the same as ``__name__``. For other functions and classes,
472it provides better information about where they were actually defined, and
473how they might be accessible from the global scope.
474
475Example with (non-bound) methods::
Nick Coghlan2dfe6b02012-01-14 14:19:49 +1000476
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100477 >>> class C:
478 ... def meth(self):
479 ... pass
480 >>> C.meth.__name__
481 'meth'
482 >>> C.meth.__qualname__
483 'C.meth'
484
485Example with nested classes::
486
487 >>> class C:
488 ... class D:
489 ... def meth(self):
490 ... pass
491 ...
492 >>> C.D.__name__
493 'D'
494 >>> C.D.__qualname__
495 'C.D'
496 >>> C.D.meth.__name__
497 'meth'
498 >>> C.D.meth.__qualname__
499 'C.D.meth'
500
501Example with nested functions::
502
503 >>> def outer():
504 ... def inner():
505 ... pass
506 ... return inner
507 ...
508 >>> outer().__name__
509 'inner'
510 >>> outer().__qualname__
511 'outer.<locals>.inner'
512
Antoine Pitroue7ede062011-11-25 19:11:26 +0100513The string representation of those objects is also changed to include the
Antoine Pitrou6bbd76b2011-11-25 19:10:05 +0100514new, more precise information::
515
516 >>> str(C.D)
517 "<class '__main__.C.D'>"
518 >>> str(C.D.meth)
519 '<function C.D.meth at 0x7f46b9fe31e0>'
520
521
Antoine Pitrouc907de92012-08-21 00:53:06 +0200522.. _pep-412:
523
Antoine Pitroud94adb72012-07-07 17:33:42 +0200524PEP 412: Key-Sharing Dictionary
525===============================
526
527:pep:`412` - Key-Sharing Dictionary
528 PEP written and implemented by Mark Shannon.
529
530Dictionaries used for the storage of objects' attributes are now able to
531share part of their internal storage between each other (namely, the part
532which stores the keys and their respective hashes). This reduces the memory
533consumption of programs creating many instances of non-builtin types.
534
535
Andrew Svetlovac23c9e2012-08-13 21:27:56 +0300536PEP 362: Function Signature Object
537==================================
538
539:pep:`362`: - Function Signature Object
540 PEP written by Brett Cannon, Yury Selivanov, Larry Hastings, Jiwon Seo.
541 Implemented by Yury Selivanov.
542
543A new function :func:`inspect.signature` makes introspection of python
544callables easy and straightforward. A broad range of callables is supported:
545python functions, decorated or not, classes, and :func:`functools.partial`
546objects. New classes :class:`inspect.Signature`, :class:`inspect.Parameter`
547and :class:`inspect.BoundArguments` hold information about the call signatures,
548such as, annotations, default values, parameters kinds, and bound arguments,
549which considerably simplifies writing decorators and any code that validates
550or amends calling signatures or arguments.
551
552
Antoine Pitrouc907de92012-08-21 00:53:06 +0200553.. _importlib:
554
Brett Cannonc2043482012-04-29 20:59:41 -0400555Using importlib as the Implementation of Import
556===============================================
557:issue:`2377` - Replace __import__ w/ importlib.__import__
558:issue:`13959` - Re-implement parts of :mod:`imp` in pure Python
559:issue:`14605` - Make import machinery explicit
560:issue:`14646` - Require loaders set __loader__ and __package__
561
562(Written by Brett Cannon)
563
564The :func:`__import__` function is now powered by :func:`importlib.__import__`.
565This work leads to the completion of "phase 2" of :pep:`302`. There are
566multiple benefits to this change. First, it has allowed for more of the
567machinery powering import to be exposed instead of being implicit and hidden
568within the C code. It also provides a single implementation for all Python VMs
569supporting Python 3.3 to use, helping to end any VM-specific deviations in
570import semantics. And finally it eases the maintenance of import, allowing for
571future growth to occur.
572
573For the common user, this change should result in no visible change in
574semantics. Any possible changes required in one's code to handle this change
575should read the `Porting Python code`_ section of this document to see what
576needs to be changed, but it will only affect those that currently manipulate
577import or try calling it programmatically.
578
579New APIs
580--------
581One of the large benefits of this work is the exposure of what goes into
582making the import statement work. That means the various importers that were
583once implicit are now fully exposed as part of the :mod:`importlib` package.
584
Brett Cannon077ef452012-08-02 17:50:06 -0400585The abstract base classes defined in :mod:`importlib.abc` have been expanded
586to properly delineate between :term:`meta path finders <meta path finder>`
587and :term:`path entry finders <path entry finder>` by introducing
588:class:`importlib.abc.MetaPathFinder` and
589:class:`importlib.abc.PathEntryFinder`, respectively. The old ABC of
590:class:`importlib.abc.Finder` is now only provided for backwards-compatibility
591and does not enforce any method requirements.
592
593In terms of finders, :class:`importlib.machinery.FileFinder` exposes the
Brett Cannonc2043482012-04-29 20:59:41 -0400594mechanism used to search for source and bytecode files of a module. Previously
595this class was an implicit member of :attr:`sys.path_hooks`.
596
597For loaders, the new abstract base class :class:`importlib.abc.FileLoader` helps
598write a loader that uses the file system as the storage mechanism for a module's
599code. The loader for source files
600(:class:`importlib.machinery.SourceFileLoader`), sourceless bytecode files
601(:class:`importlib.machinery.SourcelessFileLoader`), and extension modules
602(:class:`importlib.machinery.ExtensionFileLoader`) are now available for
603direct use.
604
605:exc:`ImportError` now has ``name`` and ``path`` attributes which are set when
606there is relevant data to provide. The message for failed imports will also
607provide the full name of the module now instead of just the tail end of the
608module's name.
609
610The :func:`importlib.invalidate_caches` function will now call the method with
611the same name on all finders cached in :attr:`sys.path_importer_cache` to help
612clean up any stored state as necessary.
613
614Visible Changes
615---------------
616[For potential required changes to code, see the `Porting Python code`_
617section]
618
619Beyond the expanse of what :mod:`importlib` now exposes, there are other
620visible changes to import. The biggest is that :attr:`sys.meta_path` and
Brett Cannon077ef452012-08-02 17:50:06 -0400621:attr:`sys.path_hooks` now store all of the meta path finders and path entry
622hooks used by import. Previously the finders were implicit and hidden within
623the C code of import instead of being directly exposed. This means that one can
624now easily remove or change the order of the various finders to fit one's needs.
Brett Cannonc2043482012-04-29 20:59:41 -0400625
626Another change is that all modules have a ``__loader__`` attribute, storing the
627loader used to create the module. :pep:`302` has been updated to make this
628attribute mandatory for loaders to implement, so in the future once 3rd-party
629loaders have been updated people will be able to rely on the existence of the
630attribute. Until such time, though, import is setting the module post-load.
631
632Loaders are also now expected to set the ``__package__`` attribute from
633:pep:`366`. Once again, import itself is already setting this on all loaders
634from :mod:`importlib` and import itself is setting the attribute post-load.
635
636``None`` is now inserted into :attr:`sys.path_importer_cache` when no finder
637can be found on :attr:`sys.path_hooks`. Since :class:`imp.NullImporter` is not
638directly exposed on :attr:`sys.path_hooks` it could no longer be relied upon to
639always be available to use as a value representing no finder found.
640
641All other changes relate to semantic changes which should be taken into
642consideration when updating code for Python 3.3, and thus should be read about
643in the `Porting Python code`_ section of this document.
644
645
R David Murray0fa2edd2012-05-25 17:59:56 -0400646New Email Package Features
647==========================
648
R David Murraycb448cf2012-05-25 22:25:56 -0400649Policy Framework
650----------------
651
R David Murray0fa2edd2012-05-25 17:59:56 -0400652The email package now has a :mod:`~email.policy` framework. A
653:class:`~email.policy.Policy` is an object with several methods and properties
654that control how the email package behaves. The primary policy for Python 3.3
655is the :class:`~email.policy.Compat32` policy, which provides backward
656compatibility with the email package in Python 3.2. A ``policy`` can be
657specified when an email message is parsed by a :mod:`~email.parser`, or when a
658:class:`~email.message.Message` object is created, or when an email is
659serialized using a :mod:`~email.generator`. Unless overridden, a policy passed
660to a ``parser`` is inherited by all the ``Message`` object and sub-objects
661created by the ``parser``. By default a ``generator`` will use the policy of
662the ``Message`` object it is serializing. The default policy is
663:data:`~email.policy.compat32`.
664
665The minimum set of controls implemented by all ``policy`` objects are:
666
667 =============== =======================================================
668 max_line_length The maximum length, excluding the linesep character(s),
669 individual lines may have when a ``Message`` is
670 serialized. Defaults to 78.
671
672 linesep The character used to separate individual lines when a
673 ``Message`` is serialized. Defaults to ``\n``.
674
675 cte_type ``7bit`` or ``8bit``. ``8bit`` applies only to a
676 ``Bytes`` ``generator``, and means that non-ASCII may
677 be used where allowed by the protocol (or where it
678 exists in the original input).
679
680 raise_on_defect Causes a ``parser`` to raise error when defects are
681 encountered instead of adding them to the ``Message``
682 object's ``defects`` list.
683 =============== =======================================================
684
685A new policy instance, with new settings, is created using the
686:meth:`~email.policy.Policy.clone` method of policy objects. ``clone`` takes
687any of the above controls as keyword arguments. Any control not specified in
688the call retains its default value. Thus you can create a policy that uses
689``\r\n`` linesep characters like this::
690
Georg Brandl3539afd2012-05-30 22:03:20 +0200691 mypolicy = compat32.clone(linesep='\r\n')
R David Murray0fa2edd2012-05-25 17:59:56 -0400692
693Policies can be used to make the generation of messages in the format needed by
694your application simpler. Instead of having to remember to specify
695``linesep='\r\n'`` in all the places you call a ``generator``, you can specify
696it once, when you set the policy used by the ``parser`` or the ``Message``,
697whichever your program uses to create ``Message`` objects. On the other hand,
698if you need to generate messages in multiple forms, you can still specify the
699parameters in the appropriate ``generator`` call. Or you can have custom
700policy instances for your different cases, and pass those in when you create
701the ``generator``.
702
703
R David Murraycb448cf2012-05-25 22:25:56 -0400704Provisional Policy with New Header API
705--------------------------------------
706
707While the policy framework is worthwhile all by itself, the main motivation for
708introducing it is to allow the creation of new policies that implement new
709features for the email package in a way that maintains backward compatibility
710for those who do not use the new policies. Because the new policies introduce a
711new API, we are releasing them in Python 3.3 as a :term:`provisional policy
712<provisional package>`. Backwards incompatible changes (up to and including
713removal of the code) may occur if deemed necessary by the core developers.
714
715The new policies are instances of :class:`~email.policy.EmailPolicy`,
716and add the following additional controls:
717
718 =============== =======================================================
719 refold_source Controls whether or not headers parsed by a
720 :mod:`~email.parser` are refolded by the
721 :mod:`~email.generator`. It can be ``none``, ``long``,
722 or ``all``. The default is ``long``, which means that
723 source headers with a line longer than
724 ``max_line_length`` get refolded. ``none`` means no
725 line get refolded, and ``all`` means that all lines
726 get refolded.
727
728 header_factory A callable that take a ``name`` and ``value`` and
729 produces a custom header object.
730 =============== =======================================================
731
732The ``header_factory`` is the key to the new features provided by the new
733policies. When one of the new policies is used, any header retrieved from
734a ``Message`` object is an object produced by the ``header_factory``, and any
735time you set a header on a ``Message`` it becomes an object produced by
736``header_factory``. All such header objects have a ``name`` attribute equal
737to the header name. Address and Date headers have additional attributes
738that give you access to the parsed data of the header. This means you can now
739do things like this::
740
741 >>> m = Message(policy=SMTP)
742 >>> m['To'] = 'Éric <foo@example.com>'
743 >>> m['to']
744 'Éric <foo@example.com>'
745 >>> m['to'].addresses
746 (Address(display_name='Éric', username='foo', domain='example.com'),)
747 >>> m['to'].addresses[0].username
748 'foo'
749 >>> m['to'].addresses[0].display_name
750 'Éric'
751 >>> m['Date'] = email.utils.localtime()
752 >>> m['Date'].datetime
753 datetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))
754 >>> m['Date']
755 'Fri, 25 May 2012 21:44:27 -0400'
756 >>> print(m)
757 To: =?utf-8?q?=C3=89ric?= <foo@example.com>
758 Date: Fri, 25 May 2012 21:44:27 -0400
759
760You will note that the unicode display name is automatically encoded as
761``utf-8`` when the message is serialized, but that when the header is accessed
762directly, you get the unicode version. This eliminates any need to deal with
763the :mod:`email.header` :meth:`~email.header.decode_header` or
764:meth:`~email.header.make_header` functions.
765
766You can also create addresses from parts::
767
768 >>> m['cc'] = [Group('pals', [Address('Bob', 'bob', 'example.com'),
769 ... Address('Sally', 'sally', 'example.com')]),
770 ... Address('Bonzo', addr_spec='bonz@laugh.com')]
771 >>> print(m)
772 To: =?utf-8?q?=C3=89ric?= <foo@example.com>
773 Date: Fri, 25 May 2012 21:44:27 -0400
774 cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>
775
776Decoding to unicode is done automatically::
777
778 >>> m2 = message_from_string(str(m))
779 >>> m2['to']
780 'Éric <foo@example.com>'
781
782When you parse a message, you can use the ``addresses`` and ``groups``
783attributes of the header objects to access the groups and individual
784addresses::
785
786 >>> m2['cc'].addresses
787 (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'))
788 >>> m2['cc'].groups
789 (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'),))
790
791In summary, if you use one of the new policies, header manipulation works the
792way it ought to: your application works with unicode strings, and the email
793package transparently encodes and decodes the unicode to and from the RFC
794standard Content Transfer Encodings.
795
796
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000797Other Language Changes
798======================
799
800Some smaller changes made to the core Python language are:
801
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100802* Added support for Unicode name aliases and named sequences.
803 Both :func:`unicodedata.lookup()` and ``'\N{...}'`` now resolve name aliases,
804 and :func:`unicodedata.lookup()` resolves named sequences too.
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000805
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100806 (Contributed by Ezio Melotti in :issue:`12753`)
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300807
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100808* Equality comparisons on :func:`range` objects now return a result reflecting
809 the equality of the underlying sequences generated by those range objects.
Ezio Melotti931b8aa2011-10-21 21:57:36 +0300810
Sandro Tosicd899122012-01-22 12:16:04 +0100811 (:issue:`13201`)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000812
Antoine Pitrou7b578b32011-11-29 22:47:11 +0100813* The ``count()``, ``find()``, ``rfind()``, ``index()`` and ``rindex()``
814 methods of :class:`bytes` and :class:`bytearray` objects now accept an
815 integer between 0 and 255 as their first argument.
Mark Dickinson36645682011-10-23 19:53:01 +0100816
Petri Lehtinen6c3f1dd2012-06-26 10:23:07 +0300817 (Contributed by Petri Lehtinen in :issue:`12170`)
Mark Dickinson36645682011-10-23 19:53:01 +0100818
Eli Bendersky7add4ea2012-03-17 15:14:35 +0200819* New methods have been added to :class:`list` and :class:`bytearray`:
820 ``copy()`` and ``clear()``.
821
822 (:issue:`10516`)
Petri Lehtinen61ea8a02011-11-24 22:00:46 +0200823
Antoine Pitrou9a864472012-05-04 23:15:47 +0200824* Raw bytes literals can now be written ``rb"..."`` as well as ``br"..."``.
825 (Contributed by Antoine Pitrou in :issue:`13748`.)
826
827* :meth:`dict.setdefault` now does only one lookup for the given key, making
828 it atomic when used with built-in types.
829 (Contributed by Filip Gruszczyński in :issue:`13521`.)
830
831
Benjamin Petersone50d6ab2012-04-03 00:52:18 -0400832.. XXX mention new error messages for passing wrong number of arguments to functions
833
Antoine Pitrou9a864472012-05-04 23:15:47 +0200834
Antoine Pitrou79341e72012-05-17 21:13:45 +0200835A Finer-Grained Import Lock
836===========================
837
838Previous versions of CPython have always relied on a global import lock.
839This led to unexpected annoyances, such as deadlocks when importing a module
840would trigger code execution in a different thread as a side-effect.
841Clumsy workarounds were sometimes employed, such as the
842:c:func:`PyImport_ImportModuleNoBlock` C API function.
843
844In Python 3.3, importing a module takes a per-module lock. This correctly
845serializes importation of a given module from multiple threads (preventing
846the exposure of incompletely initialized modules), while eliminating the
847aforementioned annoyances.
848
849(contributed by Antoine Pitrou in :issue:`9260`.)
850
851
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200852Builtin functions and types
853===========================
Victor Stinnerfa0d6282012-08-05 15:56:51 +0200854
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200855* :func:`open` gets a new *opener* parameter: the underlying file descriptor
856 for the file object is then obtained by calling *opener* with (*file*,
857 *flags*). It can be used to use custom flags like :data:`os.O_CLOEXEC` for
858 example. The ``'x'`` mode was added: open for exclusive creation, failing if
859 the file already exists.
860* :func:`print`: added the *flush* keyword argument. If the *flush* keyword
861 argument is true, the stream is forcibly flushed.
862* :func:`hash`: hash randomization is enabled by default, see
863 :meth:`object.__hash__` and :envvar:`PYTHONHASHSEED`.
864* The :class:`str` type gets a new :meth:`~str.casefold` method: return a
865 casefolded copy of the string, casefolded strings may be used for caseless
866 matching. For example, ``'ß'.casefold()`` returns ``'ss'``.
Nick Coghlan273069c2012-08-20 17:14:07 +1000867* The sequence documentation has been substantially rewritten to better
868 explain the binary/text sequence distinction and to provide specific
869 documentation sections for the individual builtin sequence types
870 (:issue:`4966`)
Victor Stinnerfa0d6282012-08-05 15:56:51 +0200871
Victor Stinner636130e2012-08-05 16:37:12 +0200872New Modules
873===========
874
875faulthandler
876------------
877
878This new debug module contains functions to dump Python tracebacks explicitly,
879on a fault (a crash like a segmentation fault), after a timeout, or on a user
880signal. Call :func:`faulthandler.enable` to install fault handlers for the
881:const:`SIGSEGV`, :const:`SIGFPE`, :const:`SIGABRT`, :const:`SIGBUS`, and
882:const:`SIGILL` signals. You can also enable them at startup by setting the
883:envvar:`PYTHONFAULTHANDLER` environment variable or by using :option:`-X`
884``faulthandler`` command line option.
885
886Example of a segmentation fault on Linux: ::
887
888 $ python -q -X faulthandler
889 >>> import ctypes
890 >>> ctypes.string_at(0)
891 Fatal Python error: Segmentation fault
892
893 Current thread 0x00007fb899f39700:
894 File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
895 File "<stdin>", line 1 in <module>
896 Segmentation fault
897
898
899ipaddress
900---------
901
902The new :mod:`ipaddress` module provides tools for creating and manipulating
903objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e.
904an IP address associated with a specific IP subnet).
905
906(Contributed by Google and Peter Moody in :pep:`3144`)
907
908lzma
909----
910
911The newly-added :mod:`lzma` module provides data compression and decompression
912using the LZMA algorithm, including support for the ``.xz`` and ``.lzma``
913file formats.
914
915(Contributed by Nadeem Vawda and Per Øyvind Karlsen in :issue:`6715`)
916
917
918Improved Modules
919================
Giampaolo Rodolà3108f982011-02-24 20:59:48 +0000920
Victor Stinnerf4c54ff2012-02-08 01:48:34 +0100921abc
922---
923
924Improved support for abstract base classes containing descriptors composed with
925abstract methods. The recommended approach to declaring abstract descriptors is
926now to provide :attr:`__isabstractmethod__` as a dynamically updated
927property. The built-in descriptors have been updated accordingly.
928
929 * :class:`abc.abstractproperty` has been deprecated, use :class:`property`
930 with :func:`abc.abstractmethod` instead.
931 * :class:`abc.abstractclassmethod` has been deprecated, use
932 :class:`classmethod` with :func:`abc.abstractmethod` instead.
933 * :class:`abc.abstractstaticmethod` has been deprecated, use
934 :class:`staticmethod` with :func:`abc.abstractmethod` instead.
935
936(Contributed by Darren Dale in :issue:`11610`)
937
Meador Ingec5dbb3d2011-09-20 21:48:16 -0500938array
939-----
940
941The :mod:`array` module supports the :c:type:`long long` type using ``q`` and
942``Q`` type codes.
943
944(Contributed by Oren Tirosh and Hirokazu Yamamoto in :issue:`1172711`)
945
946
Victor Stinner8f17c1c2012-08-05 16:31:32 +0200947base64, binascii
948----------------
949
950ASCII-only Unicode strings are now accepted by the decoding functions of the
951modern interface. For example, ``base64.b64decode('YWJj')`` returns ``b'abc'``.
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
1019number of mappings as a single unit.
1020
1021(Written by Raymond Hettinger for :issue:`11089`, made public in
1022:issue:`11297`)
1023
1024The abstract base classes have been moved in a new :mod:`collections.abc`
1025module, to better differentiate between the abstract and the concrete
1026collections classes. Aliases for ABCs are still present in the
1027:mod:`collections` module to preserve existing imports.
1028
1029(:issue:`11085`)
1030
1031.. XXX addition of __slots__ to ABCs not recorded here: internal detail
1032
1033
Nick Coghlan3267a302012-05-21 22:54:43 +10001034contextlib
1035----------
1036
1037:class:`~collections.ExitStack` now provides a solid foundation for
1038programmatic 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`
1077 instances don't raise :exc:`TypeError`.
1078 * New :meth:`datetime.datetime.timestamp` method: Return POSIX timestamp
1079 corresponding to the :class:`~datetime.datetime` instance.
1080 * The :meth:`datetime.datetime.strftime` method supports formatting years
1081 older than 1000.
1082
1083
Stefan Krah1919b7e2012-03-21 18:25:23 +01001084decimal
1085-------
1086
1087:issue:`7652` - integrate fast native decimal arithmetic.
1088 C-module and libmpdec written by Stefan Krah.
1089
1090The new C version of the decimal module integrates the high speed libmpdec
Stefan Krahbf803082012-04-01 13:07:24 +02001091library for arbitrary precision correctly-rounded decimal floating point
1092arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001093
Stefan Krah0c0914e2012-04-09 20:31:15 +02001094Performance gains range from 10x for database applications to 100x for
Stefan Krahbf803082012-04-01 13:07:24 +02001095numerically intensive applications. These numbers are expected gains
1096for standard precisions used in decimal floating point arithmetic. Since
1097the precision is user configurable, the exact figures may vary. For example,
1098in integer bignum arithmetic the differences can be significantly higher.
1099
1100The following table is meant as an illustration. Benchmarks are available
Georg Brandl204e7892012-04-01 13:10:58 +02001101at http://www.bytereef.org/mpdecimal/quickstart.html.
Stefan Krah1919b7e2012-03-21 18:25:23 +01001102
1103 +---------+-------------+--------------+-------------+
1104 | | decimal.py | _decimal | speedup |
1105 +=========+=============+==============+=============+
Stefan Krah0c0914e2012-04-09 20:31:15 +02001106 | pi | 38.89s | 0.38s | 100x |
Stefan Krah1919b7e2012-03-21 18:25:23 +01001107 +---------+-------------+--------------+-------------+
1108 | telco | 172.19s | 5.68s | 30x |
1109 +---------+-------------+--------------+-------------+
1110 | psycopg | 3.57s | 0.29s | 12x |
1111 +---------+-------------+--------------+-------------+
1112
1113Features
1114~~~~~~~~
1115
1116* The :exc:`~decimal.FloatOperation` signal optionally enables stricter
1117 semantics for mixing floats and Decimals.
1118
1119* If Python is compiled without threads, the C version automatically
1120 disables the expensive thread local context machinery. In this case,
1121 the variable :data:`~decimal.HAVE_THREADS` is set to False.
1122
1123API changes
1124~~~~~~~~~~~
1125
1126* The C module has the following context limits, depending on the machine
1127 architecture:
1128
1129 +-------------------+---------------------+------------------------------+
1130 | | 32-bit | 64-bit |
1131 +===================+=====================+==============================+
1132 | :const:`MAX_PREC` | :const:`425000000` | :const:`999999999999999999` |
1133 +-------------------+---------------------+------------------------------+
1134 | :const:`MAX_EMAX` | :const:`425000000` | :const:`999999999999999999` |
1135 +-------------------+---------------------+------------------------------+
1136 | :const:`MIN_EMIN` | :const:`-425000000` | :const:`-999999999999999999` |
1137 +-------------------+---------------------+------------------------------+
1138
1139* In the context templates (:class:`~decimal.DefaultContext`,
1140 :class:`~decimal.BasicContext` and :class:`~decimal.ExtendedContext`)
1141 the magnitude of :attr:`~decimal.Context.Emax` and
1142 :attr:`~decimal.Context.Emin` has changed to :const:`999999`.
1143
1144* The :class:`~decimal.Decimal` constructor in decimal.py does not observe
1145 the context limits and converts values with arbitrary exponents or precision
1146 exactly. Since the C version has internal limits, the following scheme is
1147 used: If possible, values are converted exactly, otherwise
1148 :exc:`~decimal.InvalidOperation` is raised and the result is NaN. In the
1149 latter case it is always possible to use :meth:`~decimal.Context.create_decimal`
1150 in order to obtain a rounded or inexact value.
1151
1152
1153* The power function in decimal.py is always correctly-rounded. In the
1154 C version, it is defined in terms of the correctly-rounded
1155 :meth:`~decimal.Decimal.exp` and :meth:`~decimal.Decimal.ln` functions,
1156 but the final result is only "almost always correctly rounded".
1157
1158
1159* In the C version, the context dictionary containing the signals is a
1160 :class:`~collections.abc.MutableMapping`. For speed reasons,
1161 :attr:`~decimal.Context.flags` and :attr:`~decimal.Context.traps` always
1162 refer to the same :class:`~collections.abc.MutableMapping` that the context
1163 was initialized with. If a new signal dictionary is assigned,
1164 :attr:`~decimal.Context.flags` and :attr:`~decimal.Context.traps`
1165 are updated with the new values, but they do not reference the RHS
1166 dictionary.
1167
1168
1169* Pickling a :class:`~decimal.Context` produces a different output in order
1170 to have a common interchange format for the Python and C versions.
1171
1172
1173* The order of arguments in the :class:`~decimal.Context` constructor has been
1174 changed to match the order displayed by :func:`repr`.
1175
1176
Victor Stinner811db3b2011-09-21 03:20:03 +02001177ftplib
1178------
1179
1180The :class:`~ftplib.FTP_TLS` class now provides a new
1181:func:`~ftplib.FTP_TLS.ccc` function to revert control channel back to
Florent Xicluna6d57d212011-10-23 22:23:57 +02001182plaintext. This can be useful to take advantage of firewalls that know how to
Victor Stinner811db3b2011-09-21 03:20:03 +02001183handle NAT with non-secure FTP without opening fixed ports.
1184
1185(Contributed by Giampaolo Rodolà in :issue:`12139`)
1186
1187
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001188gc
1189--
1190
1191It is now possible to register callbacks invoked by the garbage collector
Georg Brandla81b4812012-08-11 08:43:59 +02001192before and after collection using the new :data:`~gc.callbacks` list.
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001193
1194
Christian Heimes31940372012-06-26 10:16:55 +02001195hmac
1196----
1197
1198A new :func:`~hmac.compare_digest` function has been added to prevent
1199side channel attacks on digests through timing analysis.
1200
1201(Contributed by Nick Coghlan and Christian Heimes in issue:`15061`)
1202
1203
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01001204imaplib
1205-------
1206
1207The :class:`~imaplib.IMAP4_SSL` constructor now accepts an SSLContext
1208parameter to control parameters of the secure channel.
1209
1210(Contributed by Sijin Joseph in :issue:`8808`)
1211
1212
Nick Coghlan2f92e542012-06-23 19:39:55 +10001213inspect
1214-------
1215
1216A new :func:`~inspect.getclosurevars` function has been added. This function
1217reports the current binding of all names referenced from the function body and
1218where those names were resolved, making it easier to verify correct internal
1219state when testing code that relies on stateful closures.
1220
1221(Contributed by Meador Inge and Nick Coghlan in :issue:`13062`)
1222
Nick Coghlan04e2e3f2012-06-23 19:52:05 +10001223A new :func:`~inspect.getgeneratorlocals` function has been added. This
1224function reports the current binding of local variables in the generator's
1225stack frame, making it easier to verify correct internal state when testing
1226generators.
1227
1228(Contributed by Meador Inge in :issue:`15153`)
1229
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001230io
1231--
1232
Charles-François Natalid612de12012-01-14 11:51:00 +01001233The :func:`~io.open` function has a new ``'x'`` mode that can be used to
1234exclusively create a new file, and raise a :exc:`FileExistsError` if the file
1235already exists. It is based on the C11 'x' mode to fopen().
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001236
1237(Contributed by David Townshend in :issue:`12760`)
1238
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001239The constructor of the :class:`~io.TextIOWrapper` class has a new
1240*write_through* optional argument. If *write_through* is ``True``, calls to
1241:meth:`~io.TextIOWrapper.write` are guaranteed not to be buffered: any data
1242written on the :class:`~io.TextIOWrapper` object is immediately handled to its
1243underlying binary buffer.
1244
Charles-François Natalidc3044c2012-01-09 22:40:02 +01001245
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001246math
1247----
1248
1249The :mod:`math` module has a new function:
1250
1251 * :func:`~math.log2`: return the base-2 logarithm of *x*
1252 (Written by Mark Dickinson in :issue:`11888`).
1253
1254
Antoine Pitrou9a864472012-05-04 23:15:47 +02001255multiprocessing
1256---------------
1257
1258The new :func:`multiprocessing.connection.wait` function allows to poll
1259multiple objects (such as connections, sockets and pipes) with a timeout.
1260(Contributed by Richard Oudkerk in :issue:`12328`.)
1261
1262:class:`multiprocessing.Connection` objects can now be transferred over
1263multiprocessing connections.
1264(Contributed by Richard Oudkerk in :issue:`4892`.)
1265
1266
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001267nntplib
1268-------
1269
1270The :class:`nntplib.NNTP` class now supports the context manager protocol to
1271unconditionally consume :exc:`socket.error` exceptions and to close the NNTP
1272connection when done::
1273
1274 >>> from nntplib import NNTP
Ezio Melotti3c14b4e2011-07-13 11:44:44 +03001275 >>> with NNTP('news.gmane.org') as n:
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001276 ... n.group('gmane.comp.python.committers')
1277 ...
Ezio Melotti04f648c2011-07-26 09:37:46 +03001278 ('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001279 >>>
1280
1281(Contributed by Giampaolo Rodolà in :issue:`9795`)
1282
1283
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001284os
1285--
1286
Charles-François Natalia003af12011-06-01 20:30:52 +02001287* The :mod:`os` module has a new :func:`~os.pipe2` function that makes it
1288 possible to create a pipe with :data:`~os.O_CLOEXEC` or
1289 :data:`~os.O_NONBLOCK` flags set atomically. This is especially useful to
1290 avoid race conditions in multi-threaded programs.
1291
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001292* The :mod:`os` module has a new :func:`~os.sendfile` function which provides
1293 an efficent "zero-copy" way for copying data from one file (or socket)
1294 descriptor to another. The phrase "zero-copy" refers to the fact that all of
1295 the copying of data between the two descriptors is done entirely by the
1296 kernel, with no copying of data into userspace buffers. :func:`~os.sendfile`
1297 can be used to efficiently copy data from a file on disk to a network socket,
1298 e.g. for downloading a file.
Giampaolo Rodolàc9c2c8b2011-02-25 14:39:16 +00001299
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001300 (Patch submitted by Ross Lagerwall and Giampaolo Rodolà in :issue:`10882`.)
1301
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001302* To avoid race conditions like symlink attacks and issues with temporary
1303 files and directories, it is more reliable (and also faster) to manipulate
1304 file descriptors instead of file names. Python 3.3 enhances existing functions
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001305 and introduces new functions to work on file descriptors (:issue:`4761`,
1306 :issue:`10755`).
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001307
1308 - The :mod:`os` module has a new :func:`~os.fwalk` function similar to
1309 :func:`~os.walk` except that it also yields file descriptors referring to the
1310 directories visited. This is especially useful to avoid symlink races.
1311
1312 - The following functions get new optional *dir_fd* (:ref:`paths relative to
1313 directory descriptors <dir_fd>`) and/or *follow_symlinks* (:ref:`not
1314 following symlinks <follow_symlinks>`):
1315 :func:`~os.access`, :func:`~os.chflags`, :func:`~os.chmod`, :func:`~os.chown`,
1316 :func:`~os.link`, :func:`~os.lstat`, :func:`~os.mkdir`, :func:`~os.mkfifo`,
1317 :func:`~os.mknod`, :func:`~os.open`, :func:`~os.readlink`, :func:`~os.remove`,
1318 :func:`~os.rename`, :func:`~os.replace`, :func:`~os.rmdir`, :func:`~os.stat`,
1319 :func:`~os.symlink`, :func:`~os.unlink`, :func:`~os.utime`.
1320
1321 - The following functions now support a file descriptor for their path argument:
1322 :func:`~os.chdir`, :func:`~os.chmod`, :func:`~os.chown`,
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001323 :func:`~os.execve`, :func:`~os.listdir`, :func:`~os.pathconf`, :func:`~os.path.exists`,
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001324 :func:`~os.stat`, :func:`~os.statvfs`, :func:`~os.utime`.
1325
Giampaolo Rodolà18e8bcb2011-02-25 20:57:54 +00001326* The :mod:`os` module has two new functions: :func:`~os.getpriority` and
1327 :func:`~os.setpriority`. They can be used to get or set process
1328 niceness/priority in a fashion similar to :func:`os.nice` but extended to all
1329 processes instead of just the current one.
1330
1331 (Patch submitted by Giampaolo Rodolà in :issue:`10784`.)
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001332
Antoine Pitrou9a864472012-05-04 23:15:47 +02001333* The new :func:`os.replace` function allows cross-platform renaming of a
1334 file with overwriting the destination. With :func:`os.rename`, an existing
1335 destination file is overwritten under POSIX, but raises an error under
1336 Windows.
1337 (Contributed by Antoine Pitrou in :issue:`8828`.)
1338
1339* The new :func:`os.get_terminal_size` function queries the size of the
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001340 terminal attached to a file descriptor. See also
1341 :func:`shutil.get_terminal_size`.
Antoine Pitrou9a864472012-05-04 23:15:47 +02001342 (Contributed by Zbigniew Jędrzejewski-Szmek in :issue:`13609`.)
1343
Georg Brandldba3b5c2012-06-26 09:36:14 +02001344.. XXX sort out this mess after beta1
Victor Stinnere5064372011-10-14 00:08:29 +02001345
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001346* New functions to support Linux extended attributes (:issue:`12720`):
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001347 :func:`~os.getxattr`, :func:`~os.listxattr`, :func:`~os.removexattr`,
1348 :func:`~os.setxattr`.
Victor Stinnere5064372011-10-14 00:08:29 +02001349
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001350* New interface to the scheduler. These functions
1351 control how a process is allocated CPU time by the operating system. New
1352 functions:
1353 :func:`~os.sched_get_priority_max`, :func:`~os.sched_get_priority_min`,
1354 :func:`~os.sched_getaffinity`, :func:`~os.sched_getparam`,
1355 :func:`~os.sched_getscheduler`, :func:`~os.sched_rr_get_interval`,
1356 :func:`~os.sched_setaffinity`, :func:`~os.sched_setparam`,
1357 :func:`~os.sched_setscheduler`, :func:`~os.sched_yield`,
Victor Stinnere5064372011-10-14 00:08:29 +02001358
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001359* New functions to control the file system:
Victor Stinnere5064372011-10-14 00:08:29 +02001360
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001361 * :func:`~os.posix_fadvise`: Announces an intention to access data in a
1362 specific pattern thus allowing the kernel to make optimizations.
1363 * :func:`~os.posix_fallocate`: Ensures that enough disk space is allocated
1364 for a file.
1365 * :func:`~os.sync`: Force write of everything to disk.
Victor Stinnere5064372011-10-14 00:08:29 +02001366
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001367* Add some extra posix functions to the os module:
Victor Stinnere5064372011-10-14 00:08:29 +02001368
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001369 * :func:`~os.lockf`: Apply, test or remove a POSIX lock on an open file descriptor.
1370 * :func:`~os.pread`: Read from a file descriptor at an offset, the file
1371 offset remains unchanged.
1372 * :func:`~os.pwrite`: Write to a file descriptor from an offset, leaving
1373 the file offset unchanged.
1374 * :func:`~os.readv`: Read from a file descriptor into a number of writable buffers.
1375 * :func:`~os.truncate`: Truncate the file corresponding to *path*, so that
1376 it is at most *length* bytes in size.
1377 * :func:`~os.waitid`: Wait for the completion of one or more child processes.
1378 * :func:`~os.writev`: Write the contents of *buffers* to a file descriptor,
1379 where *buffers* is an arbitrary sequence of buffers.
1380 * :func:`~os.getgrouplist` (:issue:`9344`): Return list of group ids that
1381 specified user belongs to.
Victor Stinnere5064372011-10-14 00:08:29 +02001382
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001383* :func:`~os.times` and :func:`~os.uname`: Return type changed from a tuple to
1384 a tuple-like object with named attributes.
Victor Stinnere5064372011-10-14 00:08:29 +02001385
Giampaolo Rodolà424298a2011-03-03 18:34:06 +00001386
Georg Brandl4c7c3c52012-03-10 22:36:48 +01001387pdb
1388---
1389
1390* Tab-completion is now available not only for command names, but also their
1391 arguments. For example, for the ``break`` command, function and file names
1392 are completed. (Contributed by Georg Brandl in :issue:`14210`)
1393
1394
Antoine Pitrou9a864472012-05-04 23:15:47 +02001395pickle
1396------
1397
1398:class:`pickle.Pickler` objects now have an optional
1399:attr:`~pickle.Pickler.dispatch_table` attribute allowing to set per-pickler
1400reduction functions.
1401(Contributed by Richard Oudkerk in :issue:`14166`.)
1402
1403
Victor Stinner383c3fc2011-05-25 01:35:05 +02001404pydoc
1405-----
1406
Victor Stinner6daa33c2011-05-25 01:41:22 +02001407The Tk GUI and the :func:`~pydoc.serve` function have been removed from the
1408:mod:`pydoc` module: ``pydoc -g`` and :func:`~pydoc.serve` have been deprecated
1409in Python 3.2.
Victor Stinner383c3fc2011-05-25 01:35:05 +02001410
1411
Antoine Pitrouad09b5d2012-06-24 22:41:33 +02001412re
1413--
1414
1415:class:`str` regular expressions now support ``\u`` and ``\U`` escapes.
1416
1417(Contributed by Serhiy Storchaka in :issue:`3665`.)
1418
1419
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001420sched
1421-----
Victor Stinner754851f2011-04-19 23:58:51 +02001422
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001423* :meth:`~sched.scheduler.run` now accepts a *blocking* parameter which when
1424 set to False makes the method execute the scheduled events due to expire
1425 soonest (if any) and then return immediately.
1426 This is useful in case you want to use the :class:`~sched.scheduler` in
1427 non-blocking applications. (Contributed by Giampaolo Rodolà in :issue:`13449`)
Victor Stinner754851f2011-04-19 23:58:51 +02001428
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001429* :class:`~sched.scheduler` class can now be safely used in multi-threaded
1430 environments. (Contributed by Josiah Carlson and Giampaolo Rodolà in
1431 :issue:`8684`)
1432
1433* *timefunc* and *delayfunct* parameters of :class:`~sched.scheduler` class
1434 constructor are now optional and defaults to :func:`time.time` and
1435 :func:`time.sleep` respectively. (Contributed by Chris Clark in
1436 :issue:`13245`)
1437
1438* :meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs`
1439 *argument* parameter is now optional. (Contributed by Chris Clark in
1440 :issue:`13245`)
1441
1442* :meth:`~sched.scheduler.enter` and :meth:`~sched.scheduler.enterabs`
1443 now accept a *kwargs* parameter. (Contributed by Chris Clark in
1444 :issue:`13245`)
1445
1446
1447shutil
1448------
1449
1450* The :mod:`shutil` module has these new fuctions:
1451
1452 * :func:`~shutil.disk_usage`: provides total, used and free disk space
1453 statistics. (Contributed by Giampaolo Rodolà in :issue:`12442`)
1454 * :func:`~shutil.chown`: allows one to change user and/or group of the given
1455 path also specifying the user/group names and not only their numeric
1456 ids. (Contributed by Sandro Tosi in :issue:`12191`)
Victor Stinnera9293352011-04-30 15:21:58 +02001457
Antoine Pitrou9a864472012-05-04 23:15:47 +02001458* The new :func:`shutil.get_terminal_size` function returns the size of the
1459 terminal window the interpreter is attached to.
1460 (Contributed by Zbigniew Jędrzejewski-Szmek in :issue:`13609`.)
1461
1462* Several functions now take an optional ``symlinks`` argument: when that
1463 parameter is true, symlinks aren't dereferenced and the operation instead
1464 acts on the symlink itself (or creates one, if relevant).
1465 (Contributed by Hynek Schlawack in :issue:`12715`.)
1466
Nick Coghlan5b0eca12012-06-24 16:43:06 +10001467* :func:`~shutil.rmtree` is now resistant to symlink attacks on platforms
1468 which support the new ``dir_fd`` parameter in :func:`os.open` and
Georg Brandldba3b5c2012-06-26 09:36:14 +02001469 :func:`os.unlink`. (Contributed by Martin von Löwis and Hynek Schlawack
Nick Coghlan5b0eca12012-06-24 16:43:06 +10001470 in :issue:`4489`.)
1471
Antoine Pitrou9a864472012-05-04 23:15:47 +02001472
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001473
Victor Stinnera9293352011-04-30 15:21:58 +02001474signal
1475------
1476
Victor Stinnerfa0e3d52011-05-09 01:01:09 +02001477* The :mod:`signal` module has new functions:
Victor Stinnera9293352011-04-30 15:21:58 +02001478
Victor Stinnerb3e72192011-05-08 01:46:11 +02001479 * :func:`~signal.pthread_sigmask`: fetch and/or change the signal mask of the
1480 calling thread (Contributed by Jean-Paul Calderone in :issue:`8407`) ;
1481 * :func:`~signal.pthread_kill`: send a signal to a thread ;
1482 * :func:`~signal.sigpending`: examine pending functions ;
1483 * :func:`~signal.sigwait`: wait a signal.
Ross Lagerwallbc808222011-06-25 12:13:40 +02001484 * :func:`~signal.sigwaitinfo`: wait for a signal, returning detailed
1485 information about it.
1486 * :func:`~signal.sigtimedwait`: like :func:`~signal.sigwaitinfo` but with a
1487 timeout.
Victor Stinnera9293352011-04-30 15:21:58 +02001488
Victor Stinnerd49b1f12011-05-08 02:03:15 +02001489* The signal handler writes the signal number as a single byte instead of
1490 a nul byte into the wakeup file descriptor. So it is possible to wait more
1491 than one signal and know which signals were raised.
1492
Victor Stinner388196e2011-05-10 17:13:00 +02001493* :func:`signal.signal` and :func:`signal.siginterrupt` raise an OSError,
1494 instead of a RuntimeError: OSError has an errno attribute.
1495
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001496smtplib
1497-------
1498
1499The :class:`~smtplib.SMTP_SSL` constructor and the :meth:`~smtplib.SMTP.starttls`
1500method now accept an SSLContext parameter to control parameters of the secure
1501channel.
1502
1503(Contributed by Kasun Herath in :issue:`8809`)
1504
1505
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001506socket
1507------
1508
Charles-François Natali47413c12011-10-06 19:47:44 +02001509* The :class:`~socket.socket` class now exposes additional methods to process
1510 ancillary data when supported by the underlying platform:
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001511
Charles-François Natali47413c12011-10-06 19:47:44 +02001512 * :func:`~socket.socket.sendmsg`
1513 * :func:`~socket.socket.recvmsg`
1514 * :func:`~socket.socket.recvmsg_into`
Nick Coghlan96fe56a2011-08-22 11:55:57 +10001515
Charles-François Natali47413c12011-10-06 19:47:44 +02001516 (Contributed by David Watson in :issue:`6560`, based on an earlier patch by
1517 Heiko Wundram)
1518
1519* The :class:`~socket.socket` class now supports the PF_CAN protocol family
1520 (http://en.wikipedia.org/wiki/Socketcan), on Linux
1521 (http://lwn.net/Articles/253425).
1522
1523 (Contributed by Matthias Fuchs, updated by Tiago Gonçalves in :issue:`10141`)
1524
Charles-François Natali10b8cf42011-11-10 19:21:37 +01001525* The :class:`~socket.socket` class now supports the PF_RDS protocol family
1526 (http://en.wikipedia.org/wiki/Reliable_Datagram_Sockets and
1527 http://oss.oracle.com/projects/rds/).
Victor Stinner754851f2011-04-19 23:58:51 +02001528
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001529
Victor Stinner99c8b162011-05-24 12:05:19 +02001530ssl
1531---
1532
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001533* The :mod:`ssl` module has two new random generation functions:
Victor Stinner99c8b162011-05-24 12:05:19 +02001534
1535 * :func:`~ssl.RAND_bytes`: generate cryptographically strong
1536 pseudo-random bytes.
1537 * :func:`~ssl.RAND_pseudo_bytes`: generate pseudo-random bytes.
1538
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001539 (Contributed by Victor Stinner in :issue:`12049`)
1540
1541* The :mod:`ssl` module now exposes a finer-grained exception hierarchy
1542 in order to make it easier to inspect the various kinds of errors.
1543
1544 (Contributed by Antoine Pitrou in :issue:`11183`)
1545
1546* :meth:`~ssl.SSLContext.load_cert_chain` now accepts a *password* argument
1547 to be used if the private key is encrypted.
1548
1549 (Contributed by Adam Simpkins in :issue:`12803`)
1550
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001551* Diffie-Hellman key exchange, both regular and Elliptic Curve-based, is
1552 now supported through the :meth:`~ssl.SSLContext.load_dh_params` and
1553 :meth:`~ssl.SSLContext.set_ecdh_curve` methods.
1554
1555 (Contributed by Antoine Pitrou in :issue:`13626` and :issue:`13627`)
1556
Antoine Pitrou2c0a9672011-11-17 02:09:13 +01001557* SSL sockets have a new :meth:`~ssl.SSLSocket.get_channel_binding` method
1558 allowing the implementation of certain authentication mechanisms such as
1559 SCRAM-SHA-1-PLUS.
1560
1561 (Contributed by Jacek Konieczny in :issue:`12551`)
1562
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001563* You can query the SSL compression algorithm used by an SSL socket, thanks
1564 to its new :meth:`~ssl.SSLSocket.compression` method.
1565
1566 (Contributed by Antoine Pitrou in :issue:`13634`)
1567
Antoine Pitrou9a864472012-05-04 23:15:47 +02001568* Support has been added for the Next Procotol Negotiation extension using
1569 the :meth:`ssl.SSLContext.set_npn_protocols` method.
1570
1571 (Contributed by Colin Marc in :issue:`14204`)
1572
Antoine Pitrouad09b5d2012-06-24 22:41:33 +02001573* SSL errors can now be introspected more easily thanks to
1574 :attr:`~ssl.SSLError.library` and :attr:`~ssl.SSLError.reason` attributes.
1575
1576 (Contributed by Antoine Pitrou in :issue:`14837`)
1577
Giampaolo Rodola'ffa1d0b2012-05-15 15:30:25 +02001578stat
1579----
1580
1581- The undocumented tarfile.filemode function has been moved to
1582 :func:`stat.filemode`. It can be used to convert a file's mode to a string of
1583 the form '-rwxrwxrwx'.
1584
1585 (Contributed by Giampaolo Rodolà in :issue:`14807`)
Antoine Pitrou73fc8142011-12-23 20:58:36 +01001586
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001587sys
1588---
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +02001589
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001590* The :mod:`sys` module has a new :data:`~sys.thread_info` :term:`struct
1591 sequence` holding informations about the thread implementation.
Giampaolo Rodola'210e7ca2011-07-01 13:55:36 +02001592
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001593 (:issue:`11223`)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +02001594
Nick Coghlan4fae8cd2012-06-11 23:07:51 +10001595textwrap
1596--------
1597
1598* The :mod:`textwrap` module has a new :func:`~textwrap.indent` that makes
1599 it straightforward to add a common prefix to selected lines in a block
1600 of text.
1601
1602 (:issue:`13857`)
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01001603
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001604time
1605----
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01001606
Victor Stinnerec895392012-04-29 02:41:27 +02001607The :pep:`418` added new functions to the :mod:`time` module:
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001608
Victor Stinnerec895392012-04-29 02:41:27 +02001609* :func:`~time.get_clock_info`: Get information on a clock.
1610* :func:`~time.monotonic`: Monotonic clock (cannot go backward), not affected
1611 by system clock updates.
1612* :func:`~time.perf_counter`: Performance counter with the highest available
1613 resolution to measure a short duration.
1614* :func:`~time.process_time`: Sum of the system and user CPU time of the
1615 current process.
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001616
Victor Stinnerec895392012-04-29 02:41:27 +02001617Other new functions:
1618
1619* :func:`~time.clock_getres`, :func:`~time.clock_gettime` and
1620 :func:`~time.clock_settime` functions with ``CLOCK_xxx`` constants.
1621 (Contributed by Victor Stinner in :issue:`10278`)
Victor Stinnerf4c54ff2012-02-08 01:48:34 +01001622
Antoine Pitrou5a8bc6f2011-11-17 02:20:48 +01001623
Victor Stinner0db176f2012-04-16 00:16:30 +02001624types
1625-----
1626
1627Add a new :class:`types.MappingProxyType` class: Read-only proxy of a mapping.
1628(:issue:`14386`)
1629
1630
Nick Coghlan7fc570a2012-05-20 02:34:13 +10001631The new functions `types.new_class` and `types.prepare_class` provide support
1632for PEP 3115 compliant dynamic type creation. (:issue:`14588`)
1633
1634
Senthil Kumarande49d642011-10-16 23:54:44 +08001635urllib
1636------
1637
1638The :class:`~urllib.request.Request` class, now accepts a *method* argument
1639used by :meth:`~urllib.request.Request.get_method` to determine what HTTP method
Senthil Kumarana41c9422011-10-20 02:37:08 +08001640should be used. For example, this will send a ``'HEAD'`` request::
Senthil Kumarande49d642011-10-16 23:54:44 +08001641
1642 >>> urlopen(Request('http://www.python.org', method='HEAD'))
1643
1644(:issue:`1673007`)
Giampaolo Rodola'096dcb12011-06-27 11:17:51 +02001645
Giampaolo Rodola'be55d992011-11-22 13:33:34 +01001646
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001647webbrowser
1648----------
1649
1650The :mod:`webbrowser` module supports more browsers: Google Chrome (named
1651:program:`chrome`, :program:`chromium`, :program:`chrome-browser` or
1652:program:`chromium-browser` depending on the version and operating system) as
1653well as the the generic launchers :program:`xdg-open` from the FreeDesktop.org
1654project and :program:`gvfs-open` which is the default URI handler for GNOME 3.
1655
1656(:issue:`13620` and :issue:`14493`)
1657
1658
Eli Benderskyefcaba02012-08-09 08:20:20 +03001659xml.etree.ElementTree
1660---------------------
1661
1662The :mod:`xml.etree.ElementTree` module now imports its C accelerator by
1663default; there is no longer a need to explicitly import
1664:mod:`xml.etree.cElementTree` (this module stays for backwards compatibility,
1665but is now deprecated). In addition, the ``iter`` family of methods of
1666:class:`~xml.etree.ElementTree.Element` has been optimized (rewritten in C).
1667The module's documentation has also been greatly improved with added examples
1668and a more detailed reference.
1669
1670
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001671Optimizations
1672=============
1673
1674Major performance enhancements have been added:
1675
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001676* Thanks to :pep:`393`, some operations on Unicode strings have been optimized:
Victor Stinner46606ce2011-11-20 18:27:55 +01001677
1678 * the memory footprint is divided by 2 to 4 depending on the text
Victor Stinnera996f1e2011-11-21 13:14:43 +01001679 * encode an ASCII string to UTF-8 doesn't need to encode characters anymore,
1680 the UTF-8 representation is shared with the ASCII representation
Victor Stinner6099a032011-12-18 14:22:26 +01001681 * the UTF-8 encoder has been optimized
1682 * repeating a single ASCII letter and getting a substring of a ASCII strings
1683 is 4 times faster
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001684
Antoine Pitrou5d7e1d32012-06-24 22:38:23 +02001685* UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.
Antoine Pitrou5cec9d22012-05-17 17:37:02 +02001686
Antoine Pitrouc9092962012-06-15 22:22:18 +02001687 (contributed by Serhiy Storchaka, :issue:`14624`, :issue:`14738` and
1688 :issue:`15026`.)
Antoine Pitrou5cec9d22012-05-17 17:37:02 +02001689
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001690
1691Build and C API Changes
1692=======================
1693
1694Changes to Python's build process and to the C API include:
1695
Stefan Krah95b1ba62012-02-29 17:27:21 +01001696* New :pep:`3118` related function:
1697
1698 * :c:func:`PyMemoryView_FromMemory`
1699
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001700* :pep:`393` added new Unicode types, macros and functions:
Victor Stinner46606ce2011-11-20 18:27:55 +01001701
Victor Stinnera996f1e2011-11-21 13:14:43 +01001702 * High-level API:
1703
1704 * :c:func:`PyUnicode_CopyCharacters`
1705 * :c:func:`PyUnicode_FindChar`
1706 * :c:func:`PyUnicode_GetLength`, :c:macro:`PyUnicode_GET_LENGTH`
1707 * :c:func:`PyUnicode_New`
1708 * :c:func:`PyUnicode_Substring`
1709 * :c:func:`PyUnicode_ReadChar`, :c:func:`PyUnicode_WriteChar`
1710
1711 * Low-level API:
1712
1713 * :c:type:`Py_UCS1`, :c:type:`Py_UCS2`, :c:type:`Py_UCS4` types
1714 * :c:type:`PyASCIIObject` and :c:type:`PyCompactUnicodeObject` structures
1715 * :c:macro:`PyUnicode_READY`
1716 * :c:func:`PyUnicode_FromKindAndData`
1717 * :c:func:`PyUnicode_AsUCS4`, :c:func:`PyUnicode_AsUCS4Copy`
1718 * :c:macro:`PyUnicode_DATA`, :c:macro:`PyUnicode_1BYTE_DATA`,
1719 :c:macro:`PyUnicode_2BYTE_DATA`, :c:macro:`PyUnicode_4BYTE_DATA`
1720 * :c:macro:`PyUnicode_KIND` with :c:type:`PyUnicode_Kind` enum:
1721 :c:data:`PyUnicode_WCHAR_KIND`, :c:data:`PyUnicode_1BYTE_KIND`,
1722 :c:data:`PyUnicode_2BYTE_KIND`, :c:data:`PyUnicode_4BYTE_KIND`
1723 * :c:macro:`PyUnicode_READ`, :c:macro:`PyUnicode_READ_CHAR`, :c:macro:`PyUnicode_WRITE`
1724 * :c:macro:`PyUnicode_MAX_CHAR_VALUE`
1725
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001726
1727
Victor Stinnerd1be8782011-12-09 00:10:41 +01001728Deprecated
1729==========
1730
Georg Brandl0cd25c92011-04-29 13:45:54 +02001731Unsupported Operating Systems
Victor Stinnerd1be8782011-12-09 00:10:41 +01001732-----------------------------
Victor Stinnerb90db4c2011-04-26 22:48:24 +02001733
Brian Curtin49a40cd2011-05-02 22:30:06 -05001734OS/2 and VMS are no longer supported due to the lack of a maintainer.
1735
1736Windows 2000 and Windows platforms which set ``COMSPEC`` to ``command.com``
1737are no longer supported due to maintenance burden.
Victor Stinnerb90db4c2011-04-26 22:48:24 +02001738
1739
Victor Stinner46606ce2011-11-20 18:27:55 +01001740Deprecated Python modules, functions and methods
Victor Stinnerd1be8782011-12-09 00:10:41 +01001741------------------------------------------------
Victor Stinner19bd0692011-11-16 00:18:57 +01001742
Victor Stinner19bd0692011-11-16 00:18:57 +01001743* The ``unicode_internal`` codec has been deprecated because of the
Sandro Tosicd899122012-01-22 12:16:04 +01001744 :pep:`393`, use UTF-8, UTF-16 (``utf-16-le`` or ``utf-16-be``), or UTF-32
1745 (``utf-32-le`` or ``utf-32-be``)
Victor Stinner19bd0692011-11-16 00:18:57 +01001746* :meth:`ftplib.FTP.nlst` and :meth:`ftplib.FTP.dir`: use
Victor Stinner46606ce2011-11-20 18:27:55 +01001747 :meth:`ftplib.FTP.mlsd`
Victor Stinner19bd0692011-11-16 00:18:57 +01001748* :func:`platform.popen`: use the :mod:`subprocess` module. Check especially
1749 the :ref:`subprocess-replacements` section.
1750* :issue:`13374`: The Windows bytes API has been deprecated in the :mod:`os`
Victor Stinner46606ce2011-11-20 18:27:55 +01001751 module. Use Unicode filenames, instead of bytes filenames, to not depend on
Victor Stinner19bd0692011-11-16 00:18:57 +01001752 the ANSI code page anymore and to support any filename.
Florent Xiclunaa72a98f2012-02-13 11:03:30 +01001753* :issue:`13988`: The :mod:`xml.etree.cElementTree` module is deprecated. The
1754 accelerator is used automatically whenever available.
Victor Stinner47620a62012-04-29 02:52:39 +02001755* The behaviour of :func:`time.clock` depends on the platform: use the new
1756 :func:`time.perf_counter` or :func:`time.process_time` function instead,
1757 depending on your requirements, to have a well defined behaviour.
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001758* The :func:`os.stat_float_times` function is deprecated.
Victor Stinner8f17c1c2012-08-05 16:31:32 +02001759* :mod:`abc` module:
1760
1761 * :class:`abc.abstractproperty` has been deprecated, use :class:`property`
1762 with :func:`abc.abstractmethod` instead.
1763 * :class:`abc.abstractclassmethod` has been deprecated, use
1764 :class:`classmethod` with :func:`abc.abstractmethod` instead.
1765 * :class:`abc.abstractstaticmethod` has been deprecated, use
1766 :class:`staticmethod` with :func:`abc.abstractmethod` instead.
1767
Victor Stinner19bd0692011-11-16 00:18:57 +01001768
1769
Victor Stinner46606ce2011-11-20 18:27:55 +01001770Deprecated functions and types of the C API
Victor Stinnerd1be8782011-12-09 00:10:41 +01001771-------------------------------------------
Victor Stinner46606ce2011-11-20 18:27:55 +01001772
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001773The :c:type:`Py_UNICODE` has been deprecated by :pep:`393` and will be
Victor Stinner46606ce2011-11-20 18:27:55 +01001774removed in Python 4. All functions using this type are deprecated:
1775
Victor Stinner46606ce2011-11-20 18:27:55 +01001776Unicode functions and methods using :c:type:`Py_UNICODE` and
1777:c:type:`Py_UNICODE*` types:
1778
1779 * :c:macro:`PyUnicode_FromUnicode`: use :c:func:`PyUnicode_FromWideChar` or
1780 :c:func:`PyUnicode_FromKindAndData`
1781 * :c:macro:`PyUnicode_AS_UNICODE`, :c:func:`PyUnicode_AsUnicode`,
1782 :c:func:`PyUnicode_AsUnicodeAndSize`: use :c:func:`PyUnicode_AsWideCharString`
1783 * :c:macro:`PyUnicode_AS_DATA`: use :c:macro:`PyUnicode_DATA` with
1784 :c:macro:`PyUnicode_READ` and :c:macro:`PyUnicode_WRITE`
1785 * :c:macro:`PyUnicode_GET_SIZE`, :c:func:`PyUnicode_GetSize`: use
1786 :c:macro:`PyUnicode_GET_LENGTH` or :c:func:`PyUnicode_GetLength`
1787 * :c:macro:`PyUnicode_GET_DATA_SIZE`: use
1788 ``PyUnicode_GET_LENGTH(str) * PyUnicode_KIND(str)`` (only work on ready
1789 strings)
Victor Stinnerbf6e5602011-12-12 01:53:47 +01001790 * :c:func:`PyUnicode_AsUnicodeCopy`: use :c:func:`PyUnicode_AsUCS4Copy` or
1791 :c:func:`PyUnicode_AsWideCharString`
Victor Stinnerab595942011-12-17 04:59:06 +01001792 * :c:func:`PyUnicode_GetMax`
1793
Victor Stinner46606ce2011-11-20 18:27:55 +01001794
Victor Stinnera996f1e2011-11-21 13:14:43 +01001795Functions and macros manipulating Py_UNICODE* strings:
1796
1797 * :c:macro:`Py_UNICODE_strlen`: use :c:func:`PyUnicode_GetLength` or
1798 :c:macro:`PyUnicode_GET_LENGTH`
1799 * :c:macro:`Py_UNICODE_strcat`: use :c:func:`PyUnicode_CopyCharacters` or
1800 :c:func:`PyUnicode_FromFormat`
1801 * :c:macro:`Py_UNICODE_strcpy`, :c:macro:`Py_UNICODE_strncpy`,
1802 :c:macro:`Py_UNICODE_COPY`: use :c:func:`PyUnicode_CopyCharacters` or
1803 :c:func:`PyUnicode_Substring`
1804 * :c:macro:`Py_UNICODE_strcmp`: use :c:func:`PyUnicode_Compare`
1805 * :c:macro:`Py_UNICODE_strncmp`: use :c:func:`PyUnicode_Tailmatch`
1806 * :c:macro:`Py_UNICODE_strchr`, :c:macro:`Py_UNICODE_strrchr`: use
1807 :c:func:`PyUnicode_FindChar`
Victor Stinner606e19d2012-01-04 03:59:16 +01001808 * :c:macro:`Py_UNICODE_FILL`: use :c:func:`PyUnicode_Fill`
Victor Stinnerab595942011-12-17 04:59:06 +01001809 * :c:macro:`Py_UNICODE_MATCH`
Victor Stinnera996f1e2011-11-21 13:14:43 +01001810
Victor Stinner46606ce2011-11-20 18:27:55 +01001811Encoders:
1812
1813 * :c:func:`PyUnicode_Encode`: use :c:func:`PyUnicode_AsEncodedObject`
1814 * :c:func:`PyUnicode_EncodeUTF7`
Victor Stinnera996f1e2011-11-21 13:14:43 +01001815 * :c:func:`PyUnicode_EncodeUTF8`: use :c:func:`PyUnicode_AsUTF8` or
1816 :c:func:`PyUnicode_AsUTF8String`
Victor Stinner46606ce2011-11-20 18:27:55 +01001817 * :c:func:`PyUnicode_EncodeUTF32`
1818 * :c:func:`PyUnicode_EncodeUTF16`
1819 * :c:func:`PyUnicode_EncodeUnicodeEscape:` use
1820 :c:func:`PyUnicode_AsUnicodeEscapeString`
1821 * :c:func:`PyUnicode_EncodeRawUnicodeEscape:` use
1822 :c:func:`PyUnicode_AsRawUnicodeEscapeString`
1823 * :c:func:`PyUnicode_EncodeLatin1`: use :c:func:`PyUnicode_AsLatin1String`
1824 * :c:func:`PyUnicode_EncodeASCII`: use :c:func:`PyUnicode_AsASCIIString`
1825 * :c:func:`PyUnicode_EncodeCharmap`
1826 * :c:func:`PyUnicode_TranslateCharmap`
1827 * :c:func:`PyUnicode_EncodeMBCS`: use :c:func:`PyUnicode_AsMBCSString` or
1828 :c:func:`PyUnicode_EncodeCodePage` (with ``CP_ACP`` code_page)
1829 * :c:func:`PyUnicode_EncodeDecimal`,
1830 :c:func:`PyUnicode_TransformDecimalToASCII`
1831
1832
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001833Porting to Python 3.3
1834=====================
1835
1836This section lists previously described changes and other bugfixes
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001837that may require changes to your code.
1838
Barry Warsawc1e721b2012-07-30 16:24:12 -04001839.. _portingpythoncode:
1840
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001841Porting Python code
1842-------------------
Giampaolo Rodolà3108f982011-02-24 20:59:48 +00001843
Victor Stinnerfa0d6282012-08-05 15:56:51 +02001844* Hash randomization is enabled by default. Set the :envvar:`PYTHONHASHSEED`
1845 environment variable to ``0`` to disable hash randomization. See also the
1846 :meth:`object.__hash__` method.
Georg Brandld6c43402012-03-07 08:55:52 +01001847
Victor Stinner19bd0692011-11-16 00:18:57 +01001848* :issue:`12326`: On Linux, sys.platform doesn't contain the major version
Victor Stinnerff3d9392011-08-20 23:39:26 +02001849 anymore. It is now always 'linux', instead of 'linux2' or 'linux3' depending
1850 on the Linux version used to build Python. Replace sys.platform == 'linux2'
1851 with sys.platform.startswith('linux'), or directly sys.platform == 'linux' if
1852 you don't need to support older Python versions.
Éric Araujoc09fca62011-03-23 02:06:24 +01001853
Victor Stinnerecc6e662012-03-14 00:39:29 +01001854* :issue:`13847`, :issue:`14180`: :mod:`time` and :mod:`datetime`:
1855 :exc:`OverflowError` is now raised instead of :exc:`ValueError` if a
1856 timestamp is out of range. :exc:`OSError` is now raised if C functions
1857 :c:func:`gmtime` or :c:func:`localtime` failed.
1858
Brett Cannonc2043482012-04-29 20:59:41 -04001859* The default finders used by import now utilize a cache of what is contained
1860 within a specific directory. If you create a Python source file or sourceless
1861 bytecode file, make sure to call :func:`importlib.invalidate_caches` to clear
1862 out the cache for the finders to notice the new file.
1863
1864* :exc:`ImportError` now uses the full name of the module that was attemped to
1865 be imported. Doctests that check ImportErrors' message will need to be
1866 updated to use the full name of the module instead of just the tail of the
1867 name.
1868
1869* The **index** argument to :func:`__import__` now defaults to 0 instead of -1
1870 and no longer support negative values. It was an oversight when :pep:`328` was
1871 implemented that the default value remained -1. If you need to continue to
1872 perform a relative import followed by an absolute import, then perform the
1873 relative import using an index of 1, followed by another import using an
1874 index of 0. It is preferred, though, that you use
1875 :func:`importlib.import_module` rather than call :func:`__import__` directly.
1876
1877* :func:`__import__` no longer allows one to use an index value other than 0
1878 for top-level modules. E.g. ``__import__('sys', level=1)`` is now an error.
1879
1880* Because :attr:`sys.meta_path` and :attr:`sys.path_hooks` now have finders on
1881 them by default, you will most likely want to use :meth:`list.insert` instead
1882 of :meth:`list.append` to add to those lists.
1883
1884* Because ``None`` is now inserted into :attr:`sys.path_importer_cache`, if you
1885 are clearing out entries in the dictionary of paths that do not have a
1886 finder, you will need to remove keys paired with values of ``None`` **and**
Brett Cannon903c27c2012-07-09 14:15:32 -04001887 :class:`imp.NullImporter` to be backwards-compatible. This will lead to extra
Brett Cannonc2043482012-04-29 20:59:41 -04001888 overhead on older versions of Python that re-insert ``None`` into
1889 :attr:`sys.path_importer_cache` where it repesents the use of implicit
1890 finders, but semantically it should not change anything.
1891
1892* :meth:`importlib.abc.SourceLoader.path_mtime` is now deprecated in favour of
1893 :meth:`importlib.abc.SourceLoader.path_stats` as bytecode files now store
1894 both the modification time and size of the source file the bytecode file was
1895 compiled from.
1896
Brett Cannon077ef452012-08-02 17:50:06 -04001897* :class:`importlib.abc.Finder` no longer specifies a `find_module()` abstract
1898 method that must be implemented. If you were relying on subclasses to
1899 implement that method, make sure to check for the method's existence first.
1900 You will probably want to check for `find_loader()` first, though, in the
1901 case of working with :term:`path entry finders <path entry finder>`.
1902
Nick Coghlan60610002012-07-15 22:39:39 +10001903* :mod:`pkgutil` has been converted to use :mod:`importlib` internally. This
1904 eliminates many edge cases where the old behaviour of the PEP 302 import
1905 emulation failed to match the behaviour of the real import system. The
1906 import emulation itself is still present, but is now deprecated. The
1907 :func:`pkgutil.iter_importers` and :func:`pkgutil.walk_packages` functions
1908 special case the standard import hooks so they are still supported even
1909 though they do not provide the non-standard ``iter_modules()`` method.
Brett Cannon903c27c2012-07-09 14:15:32 -04001910
Brett Cannonc2043482012-04-29 20:59:41 -04001911
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001912Porting C code
1913--------------
1914
Stefan Krah54c32032012-02-29 17:47:21 +01001915* In the course of changes to the buffer API the undocumented
1916 :c:member:`~Py_buffer.smalltable` member of the
1917 :c:type:`Py_buffer` structure has been removed and the
1918 layout of the :c:type:`PyMemoryViewObject` has changed.
1919
1920 All extensions relying on the relevant parts in ``memoryobject.h``
1921 or ``object.h`` must be rebuilt.
1922
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001923* Due to :ref:`PEP 393 <pep-393>`, the :c:type:`Py_UNICODE` type and all
1924 functions using this type are deprecated (but will stay available for
1925 at least five years). If you were using low-level Unicode APIs to
1926 construct and access unicode objects and you want to benefit of the
Éric Araujo4f61a2d2012-04-04 23:01:01 -04001927 memory footprint reduction provided by PEP 393, you have to convert
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001928 your code to the new :doc:`Unicode API <../c-api/unicode>`.
1929
1930 However, if you only have been using high-level functions such as
1931 :c:func:`PyUnicode_Concat()`, :c:func:`PyUnicode_Join` or
1932 :c:func:`PyUnicode_FromFormat()`, your code will automatically take
1933 advantage of the new unicode representations.
1934
Brett Cannon77b2abd2012-07-09 16:09:00 -04001935* :c:func:`PyImport_GetMagicNumber` now returns -1 upon failure.
1936
Brett Cannon522267e2012-08-10 18:55:08 -04001937* As a negative value for the **level** argument to :func:`__import__` is no
1938 longer valid, the same now holds for :c:func:`PyImport_ImportModuleLevel`.
1939 This also means that the value of **level** used by
1940 :c:func:`PyImport_ImportModuleEx` is now 0 instead of -1.
1941
Brett Cannon77b2abd2012-07-09 16:09:00 -04001942
Antoine Pitrouc229e6e2012-02-20 19:41:11 +01001943Building C extensions
1944---------------------
1945
1946* The range of possible file names for C extensions has been narrowed.
1947 Very rarely used spellings have been suppressed: under POSIX, files
1948 named ``xxxmodule.so``, ``xxxmodule.abi3.so`` and
1949 ``xxxmodule.cpython-*.so`` are no longer recognized as implementing
1950 the ``xxx`` module. If you had been generating such files, you have
1951 to switch to the other spellings (i.e., remove the ``module`` string
1952 from the file names).
1953
1954 (implemented in :issue:`14040`.)
1955
1956
Antoine Pitrou037ffbf2011-10-24 00:25:41 +02001957Other issues
1958------------
1959
Éric Araujoc09fca62011-03-23 02:06:24 +01001960.. Issue #11591: When :program:`python` was started with :option:`-S`,
1961 ``import site`` will not add site-specific paths to the module search
1962 paths. In previous versions, it did. See changeset for doc changes in
1963 various files. Contributed by Carl Meyer with editions by Éric Araujo.
Éric Araujobe3bd572011-03-26 01:55:15 +01001964
Éric Araujobfc97292011-11-14 18:18:15 +01001965.. Issue #10998: the -Q command-line flag and related artifacts have been
Éric Araujobe3bd572011-03-26 01:55:15 +01001966 removed. Code checking sys.flags.division_warning will need updating.
1967 Contributed by Éric Araujo.