-
-
Notifications
You must be signed in to change notification settings - Fork 34.5k
Expand file tree
/
Copy path3.4.rst
More file actions
2546 lines (1900 loc) · 108 KB
/
3.4.rst
File metadata and controls
2546 lines (1900 loc) · 108 KB
Edit and raw actions
OlderNewer
1
****************************
2
What's New In Python 3.4
3
****************************
4
5
:Author: \R. David Murray <rdmurray@bitdance.com> (Editor)
6
7
.. Rules for maintenance:
8
9
* Anyone can add text to this document, but the maintainer reserves the
10
right to rewrite any additions. In particular, for obscure or esoteric
11
features, the maintainer may reduce any addition to a simple reference to
12
the new documentation rather than explaining the feature inline.
13
14
* While the maintainer will periodically go through Misc/NEWS
15
and add changes, it's best not to rely on this. We know from experience
16
that any changes that aren't in the What's New documentation around the
17
time of the original release will remain largely unknown to the community
18
for years, even if they're added later. We also know from experience that
19
other priorities can arise, and the maintainer will run out of time to do
20
updates -- in such cases, end users will be much better served by partial
21
notifications that at least give a hint about new features to
22
investigate.
23
24
* This is not a complete list of every single change; completeness
25
is the purpose of Misc/NEWS. The What's New should focus on changes that
26
are visible to Python *users* and that *require* a feature release (i.e.
27
most bug fixes should only be recorded in Misc/NEWS)
28
29
* PEPs should not be marked Final until they have an entry in What's New.
30
A placeholder entry that is just a section header and a link to the PEP
31
(e.g ":pep:`397` has been implemented") is acceptable. If a PEP has been
32
implemented and noted in What's New, don't forget to mark it as Final!
33
34
* If you want to draw your new text to the attention of the
35
maintainer, add 'XXX' to the beginning of the paragraph or
36
section.
37
38
* It's OK to add just a very brief note about a change. For
39
example: "The :ref:`~socket.transmogrify()` function was added to the
40
:mod:`socket` module." The maintainer will research the change and
41
write the necessary text (if appropriate). The advantage of doing this
42
is that even if no more descriptive text is ever added, readers will at
43
least have a notification that the new feature exists and a link to the
44
relevant documentation.
45
46
* You can comment out your additions if you like, but it's not
47
necessary (especially when a final release is some months away).
48
49
* Credit the author of a patch or bugfix. Just the name is
50
sufficient; the e-mail address isn't necessary.
51
52
* It's helpful to add the bug/patch number as a comment:
53
54
The :ref:`~socket.transmogrify()` function was added to the
55
:mod:`socket` module. (Contributed by P.Y. Developer in :issue:`12345`.)
56
57
This saves the maintainer the effort of going through the Mercurial log
58
when researching a change.
59
60
* Cross referencing tip: :ref:`mod.attr` will display as ``mod.attr``,
61
while :ref:`~mod.attr` will display as ``attr``.
62
63
This article explains the new features in Python 3.4, compared to 3.3.
64
Python 3.4 was released on March 16, 2014. For full details, see the
65
`changelog <https://docs.python.org/3.4/whatsnew/changelog.html>`_.
66
67
68
.. seealso::
69
70
:pep:`429` -- Python 3.4 Release Schedule
71
72
73
74
Summary -- Release Highlights
75
=============================
76
77
.. This section singles out the most important changes in Python 3.4.
78
Brevity is key.
79
80
New syntax features:
81
82
* No new syntax features were added in Python 3.4.
83
84
Other new features:
85
86
* :ref:`pip should always be available <whatsnew-pep-453>` (:pep:`453`).
87
* :ref:`Newly created file descriptors are non-inheritable <whatsnew-pep-446>`
88
(:pep:`446`).
89
* command line option for :ref:`isolated mode <whatsnew-isolated-mode>`
90
(:issue:`16499`).
91
* :ref:`improvements in the handling of codecs <codec-handling-improvements>`
92
that are not text encodings (multiple issues).
93
* :ref:`A ModuleSpec Type <whatsnew-pep-451>` for the Import System
94
(:pep:`451`). (Affects importer authors.)
95
* The :mod:`marshal` format has been made :ref:`more compact and efficient
96
<whatsnew-marshal-3>` (:issue:`16475`).
97
98
New library modules:
99
100
* :mod:`asyncio`: :ref:`New provisional API for asynchronous IO
101
<whatsnew-asyncio>` (:pep:`3156`).
102
* :mod:`ensurepip`: :ref:`Bootstrapping the pip installer <whatsnew-ensurepip>`
103
(:pep:`453`).
104
* :mod:`enum`: :ref:`Support for enumeration types <whatsnew-enum>`
105
(:pep:`435`).
106
* :mod:`pathlib`: :ref:`Object-oriented filesystem paths <whatsnew-pathlib>`
107
(:pep:`428`).
108
* :mod:`selectors`: :ref:`High-level and efficient I/O multiplexing
109
<whatsnew-selectors>`, built upon the :mod:`select` module primitives (part
110
of :pep:`3156`).
111
* :mod:`statistics`: A basic :ref:`numerically stable statistics library
112
<whatsnew-statistics>` (:pep:`450`).
113
* :mod:`tracemalloc`: :ref:`Trace Python memory allocations
114
<whatsnew-tracemalloc>` (:pep:`454`).
115
116
Significantly improved library modules:
117
118
* :ref:`Single-dispatch generic functions <whatsnew-singledispatch>` in
119
:mod:`functools` (:pep:`443`).
120
* New :mod:`pickle` :ref:`protocol 4 <whatsnew-protocol-4>` (:pep:`3154`).
121
* :mod:`multiprocessing` now has :ref:`an option to avoid using os.fork
122
on Unix <whatsnew-multiprocessing-no-fork>` (:issue:`8713`).
123
* :mod:`email` has a new submodule, :mod:`~email.contentmanager`, and
124
a new :mod:`~email.message.Message` subclass
125
(:class:`~email.message.EmailMessage`) that :ref:`simplify MIME
126
handling <whatsnew_email_contentmanager>` (:issue:`18891`).
127
* The :mod:`inspect` and :mod:`pydoc` modules are now capable of
128
correct introspection of a much wider variety of callable objects,
129
which improves the output of the Python :func:`help` system.
130
* The :mod:`ipaddress` module API has been declared stable
131
132
Security improvements:
133
134
* :ref:`Secure and interchangeable hash algorithm <whatsnew-pep-456>`
135
(:pep:`456`).
136
* :ref:`Make newly created file descriptors non-inheritable <whatsnew-pep-446>`
137
(:pep:`446`) to avoid leaking file descriptors to child processes.
138
* New command line option for :ref:`isolated mode <whatsnew-isolated-mode>`,
139
(:issue:`16499`).
140
* :mod:`multiprocessing` now has :ref:`an option to avoid using os.fork
141
on Unix <whatsnew-multiprocessing-no-fork>`. *spawn* and *forkserver* are
142
more secure because they avoid sharing data with child processes.
143
* :mod:`multiprocessing` child processes on Windows no longer inherit
144
all of the parent's inheritable handles, only the necessary ones.
145
* A new :func:`hashlib.pbkdf2_hmac` function provides
146
the `PKCS#5 password-based key derivation function 2
147
<https://en.wikipedia.org/wiki/PBKDF2>`_.
148
* :ref:`TLSv1.1 and TLSv1.2 support <whatsnew-tls-11-12>` for :mod:`ssl`.
149
* :ref:`Retrieving certificates from the Windows system cert store support
150
<whatsnew34-win-cert-store>` for :mod:`ssl`.
151
* :ref:`Server-side SNI (Server Name Indication) support
152
<whatsnew34-sni>` for :mod:`ssl`.
153
* The :class:`ssl.SSLContext` class has a :ref:`lot of improvements
154
<whatsnew34-sslcontext>`.
155
* All modules in the standard library that support SSL now support server
156
certificate verification, including hostname matching
157
(:func:`!ssl.match_hostname`) and CRLs (Certificate Revocation lists, see
158
:func:`ssl.SSLContext.load_verify_locations`).
159
160
CPython implementation improvements:
161
162
* :ref:`Safe object finalization <whatsnew-pep-442>` (:pep:`442`).
163
* Leveraging :pep:`442`, in most cases :ref:`module globals are no longer set
164
to None during finalization <whatsnew-pep-442>` (:issue:`18214`).
165
* :ref:`Configurable memory allocators <whatsnew-pep-445>` (:pep:`445`).
166
* :ref:`Argument Clinic <whatsnew-pep-436>` (:pep:`436`).
167
168
Please read on for a comprehensive list of user-facing changes, including many
169
other smaller improvements, CPython optimizations, deprecations, and potential
170
porting issues.
171
172
173
174
New Features
175
============
176
177
.. _whatsnew-pep-453:
178
179
PEP 453: Explicit Bootstrapping of PIP in Python Installations
180
--------------------------------------------------------------
181
182
Bootstrapping pip By Default
183
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
184
185
The new :mod:`ensurepip` module (defined in :pep:`453`) provides a standard
186
cross-platform mechanism to bootstrap the pip installer into Python
187
installations and virtual environments. The version of ``pip`` included
188
with Python 3.4.0 is ``pip`` 1.5.4, and future 3.4.x maintenance releases
189
will update the bundled version to the latest version of ``pip`` that is
190
available at the time of creating the release candidate.
191
192
By default, the commands ``pipX`` and ``pipX.Y`` will be installed on all
193
platforms (where X.Y stands for the version of the Python installation),
194
along with the ``pip`` Python package and its dependencies. On Windows and
195
in virtual environments on all platforms, the unversioned ``pip`` command
196
will also be installed. On other platforms, the system wide unversioned
197
``pip`` command typically refers to the separately installed Python 2
198
version.
199
200
The ``pyvenv`` command line utility and the :mod:`venv`
201
module make use of the :mod:`ensurepip` module to make ``pip`` readily
202
available in virtual environments. When using the command line utility,
203
``pip`` is installed by default, while when using the :mod:`venv` module
204
:ref:`venv-api` installation of ``pip`` must be requested explicitly.
205
206
For CPython :ref:`source builds on POSIX systems <building-python-on-unix>`,
207
the ``make install`` and ``make altinstall`` commands bootstrap ``pip`` by
208
default. This behaviour can be controlled through configure options, and
209
overridden through Makefile options.
210
211
On Windows and Mac OS X, the CPython installers now default to installing
212
``pip`` along with CPython itself (users may opt out of installing it
213
during the installation process). Window users will need to opt in to the
214
automatic ``PATH`` modifications to have ``pip`` available from the command
215
line by default, otherwise it can still be accessed through the Python
216
launcher for Windows as ``py -m pip``.
217
218
As :pep:`discussed in the PEP <0453#recommendations-for-downstream-distributors>`
219
platform packagers may choose not to install
220
these commands by default, as long as, when invoked, they provide clear and
221
simple directions on how to install them on that platform (usually using
222
the system package manager).
223
224
.. note::
225
226
To avoid conflicts between parallel Python 2 and Python 3 installations,
227
only the versioned ``pip3`` and ``pip3.4`` commands are bootstrapped by
228
default when ``ensurepip`` is invoked directly - the ``--default-pip``
229
option is needed to also request the unversioned ``pip`` command.
230
``pyvenv`` and the Windows installer ensure that the unqualified ``pip``
231
command is made available in those environments, and ``pip`` can always be
232
invoked via the ``-m`` switch rather than directly to avoid ambiguity on
233
systems with multiple Python installations.
234
235
236
Documentation Changes
237
~~~~~~~~~~~~~~~~~~~~~
238
239
As part of this change, the :ref:`installing-index` and
240
:ref:`distributing-index` sections of the documentation have been
241
completely redesigned as short getting started and FAQ documents. Most
242
packaging documentation has now been moved out to the Python Packaging
243
Authority maintained `Python Packaging User Guide
244
<https://packaging.python.org>`__ and the documentation of the individual
245
projects.
246
247
However, as this migration is currently still incomplete, the legacy
248
versions of those guides remaining available as :ref:`install-index`
249
and :ref:`setuptools-index`.
250
251
.. seealso::
252
253
:pep:`453` -- Explicit bootstrapping of pip in Python installations
254
PEP written by Donald Stufft and Nick Coghlan, implemented by
255
Donald Stufft, Nick Coghlan, Martin von Löwis and Ned Deily.
256
257
258
.. _whatsnew-pep-446:
259
260
PEP 446: Newly Created File Descriptors Are Non-Inheritable
261
-----------------------------------------------------------
262
263
:pep:`446` makes newly created file descriptors :ref:`non-inheritable
264
<fd_inheritance>`. In general, this is the behavior an application will
265
want: when launching a new process, having currently open files also
266
open in the new process can lead to all sorts of hard to find bugs,
267
and potentially to security issues.
268
269
However, there are occasions when inheritance is desired. To support
270
these cases, the following new functions and methods are available:
271
272
* :func:`os.get_inheritable`, :func:`os.set_inheritable`
273
* :func:`os.get_handle_inheritable`, :func:`os.set_handle_inheritable`
274
* :meth:`socket.socket.get_inheritable`, :meth:`socket.socket.set_inheritable`
275
276
.. seealso::
277
278
:pep:`446` -- Make newly created file descriptors non-inheritable
279
PEP written and implemented by Victor Stinner.
280
281
282
.. _codec-handling-improvements:
283
284
Improvements to Codec Handling
285
------------------------------
286
287
Since it was first introduced, the :mod:`codecs` module has always been
288
intended to operate as a type-neutral dynamic encoding and decoding
289
system. However, its close coupling with the Python text model, especially
290
the type restricted convenience methods on the builtin :class:`str`,
291
:class:`bytes` and :class:`bytearray` types, has historically obscured that
292
fact.
293
294
As a key step in clarifying the situation, the :meth:`codecs.encode` and
295
:meth:`codecs.decode` convenience functions are now properly documented in
296
Python 2.7, 3.3 and 3.4. These functions have existed in the :mod:`codecs`
297
module (and have been covered by the regression test suite) since Python 2.4,
298
but were previously only discoverable through runtime introspection.
299
300
Unlike the convenience methods on :class:`str`, :class:`bytes` and
301
:class:`bytearray`, the :mod:`codecs` convenience functions support arbitrary
302
codecs in both Python 2 and Python 3, rather than being limited to Unicode text
303
encodings (in Python 3) or ``basestring`` <-> ``basestring`` conversions (in
304
Python 2).
305
306
In Python 3.4, the interpreter is able to identify the known non-text
307
encodings provided in the standard library and direct users towards these
308
general purpose convenience functions when appropriate::
309
310
>>> b"abcdef".decode("hex")
311
Traceback (most recent call last):
312
File "<stdin>", line 1, in <module>
313
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs
314
315
>>> "hello".encode("rot13")
316
Traceback (most recent call last):
317
File "<stdin>", line 1, in <module>
318
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs
319
320
>>> open("foo.txt", encoding="hex")
321
Traceback (most recent call last):
322
File "<stdin>", line 1, in <module>
323
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs
324
325
In a related change, whenever it is feasible without breaking backwards
326
compatibility, exceptions raised during encoding and decoding operations
327
are wrapped in a chained exception of the same type that mentions the
328
name of the codec responsible for producing the error::
329
330
>>> import codecs
331
332
>>> codecs.decode(b"abcdefgh", "hex")
333
Traceback (most recent call last):
334
File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
335
return (binascii.a2b_hex(input), len(input))
336
binascii.Error: Non-hexadecimal digit found
337
338
The above exception was the direct cause of the following exception:
339
340
Traceback (most recent call last):
341
File "<stdin>", line 1, in <module>
342
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)
343
344
>>> codecs.encode("hello", "bz2")
345
Traceback (most recent call last):
346
File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
347
return (bz2.compress(input), len(input))
348
File "/usr/lib/python3.4/bz2.py", line 498, in compress
349
return comp.compress(data) + comp.flush()
350
TypeError: 'str' does not support the buffer interface
351
352
The above exception was the direct cause of the following exception:
353
354
Traceback (most recent call last):
355
File "<stdin>", line 1, in <module>
356
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)
357
358
Finally, as the examples above show, these improvements have permitted
359
the restoration of the convenience aliases for the non-Unicode codecs that
360
were themselves restored in Python 3.2. This means that encoding binary data
361
to and from its hexadecimal representation (for example) can now be written
362
as::
363
364
>>> from codecs import encode, decode
365
>>> encode(b"hello", "hex")
366
b'68656c6c6f'
367
>>> decode(b"68656c6c6f", "hex")
368
b'hello'
369
370
The binary and text transforms provided in the standard library are detailed
371
in :ref:`binary-transforms` and :ref:`text-transforms`.
372
373
(Contributed by Nick Coghlan in :issue:`7475`, :issue:`17827`,
374
:issue:`17828` and :issue:`19619`.)
375
376
377
.. _whatsnew-pep-451:
378
379
PEP 451: A ModuleSpec Type for the Import System
380
------------------------------------------------
381
382
:pep:`451` provides an encapsulation of the information about a module that the
383
import machinery will use to load it (that is, a module specification). This
384
helps simplify both the import implementation and several import-related APIs.
385
The change is also a stepping stone for `several future import-related
386
improvements`__.
387
388
__ https://mail.python.org/pipermail/python-dev/2013-November/130111.html
389
390
The public-facing changes from the PEP are entirely backward-compatible.
391
Furthermore, they should be transparent to everyone but importer authors. Key
392
finder and loader methods have been deprecated, but they will continue working.
393
New importers should use the new methods described in the PEP. Existing
394
importers should be updated to implement the new methods. See the
395
:ref:`deprecated-3.4` section for a list of methods that should be replaced and
396
their replacements.
397
398
399
Other Language Changes
400
----------------------
401
402
Some smaller changes made to the core Python language are:
403
404
* Unicode database updated to UCD version 6.3.
405
406
* :func:`min` and :func:`max` now accept a *default* keyword-only argument that
407
can be used to specify the value they return if the iterable they are
408
evaluating has no elements. (Contributed by Julian Berman in
409
:issue:`18111`.)
410
411
* Module objects are now :ref:`weakly referenceable <mod-weakref>`.
412
413
* Module ``__file__`` attributes (and related values) should now always
414
contain absolute paths by default, with the sole exception of
415
``__main__.__file__`` when a script has been executed directly using
416
a relative path. (Contributed by Brett Cannon in :issue:`18416`.)
417
418
* All the UTF-\* codecs (except UTF-7) now reject surrogates during both
419
encoding and decoding unless the ``surrogatepass`` error handler is used,
420
with the exception of the UTF-16 decoder (which accepts valid surrogate pairs)
421
and the UTF-16 encoder (which produces them while encoding non-BMP characters).
422
(Contributed by Victor Stinner, Kang-Hao (Kenny) Lu and Serhiy Storchaka in
423
:issue:`12892`.)
424
425
* New German EBCDIC :ref:`codec <standard-encodings>` ``cp273``. (Contributed
426
by Michael Bierenfeld and Andrew Kuchling in :issue:`1097797`.)
427
428
* New Ukrainian :ref:`codec <standard-encodings>` ``cp1125``. (Contributed by
429
Serhiy Storchaka in :issue:`19668`.)
430
431
* :class:`bytes`.join() and :class:`bytearray`.join() now accept arbitrary
432
buffer objects as arguments. (Contributed by Antoine Pitrou in
433
:issue:`15958`.)
434
435
* The :class:`int` constructor now accepts any object that has an ``__index__``
436
method for its *base* argument. (Contributed by Mark Dickinson in
437
:issue:`16772`.)
438
439
* Frame objects now have a :func:`~frame.clear` method that clears all
440
references to local variables from the frame. (Contributed by Antoine Pitrou
441
in :issue:`17934`.)
442
443
* :class:`memoryview` is now registered as a :class:`Sequence <collections.abc>`,
444
and supports the :func:`reversed` builtin. (Contributed by Nick Coghlan
445
and Claudiu Popa in :issue:`18690` and :issue:`19078`.)
446
447
* Signatures reported by :func:`help` have been modified and improved in
448
several cases as a result of the introduction of Argument Clinic and other
449
changes to the :mod:`inspect` and :mod:`pydoc` modules.
450
451
* :meth:`~object.__length_hint__` is now part of the formal language
452
specification (see :pep:`424`). (Contributed by Armin Ronacher in
453
:issue:`16148`.)
454
455
456
New Modules
457
===========
458
459
460
.. _whatsnew-asyncio:
461
462
asyncio
463
-------
464
465
The new :mod:`asyncio` module (defined in :pep:`3156`) provides a standard
466
pluggable event loop model for Python, providing solid asynchronous IO
467
support in the standard library, and making it easier for other event loop
468
implementations to interoperate with the standard library and each other.
469
470
For Python 3.4, this module is considered a :term:`provisional API`.
471
472
.. seealso::
473
474
:pep:`3156` -- Asynchronous IO Support Rebooted: the "asyncio" Module
475
PEP written and implementation led by Guido van Rossum.
476
477
478
.. _whatsnew-ensurepip:
479
480
ensurepip
481
---------
482
483
The new :mod:`ensurepip` module is the primary infrastructure for the
484
:pep:`453` implementation. In the normal course of events end users will not
485
need to interact with this module, but it can be used to manually bootstrap
486
``pip`` if the automated bootstrapping into an installation or virtual
487
environment was declined.
488
489
:mod:`ensurepip` includes a bundled copy of ``pip``, up-to-date as of the first
490
release candidate of the release of CPython with which it ships (this applies
491
to both maintenance releases and feature releases). ``ensurepip`` does not
492
access the internet. If the installation has internet access, after
493
``ensurepip`` is run the bundled ``pip`` can be used to upgrade ``pip`` to a
494
more recent release than the bundled one. (Note that such an upgraded version
495
of ``pip`` is considered to be a separately installed package and will not be
496
removed if Python is uninstalled.)
497
498
The module is named *ensure*\ pip because if called when ``pip`` is already
499
installed, it does nothing. It also has an ``--upgrade`` option that will
500
cause it to install the bundled copy of ``pip`` if the existing installed
501
version of ``pip`` is older than the bundled copy.
502
503
504
.. _whatsnew-enum:
505
506
enum
507
----
508
509
The new :mod:`enum` module (defined in :pep:`435`) provides a standard
510
implementation of enumeration types, allowing other modules (such as
511
:mod:`socket`) to provide more informative error messages and better
512
debugging support by replacing opaque integer constants with backwards
513
compatible enumeration values.
514
515
.. seealso::
516
517
:pep:`435` -- Adding an Enum type to the Python standard library
518
PEP written by Barry Warsaw, Eli Bendersky and Ethan Furman,
519
implemented by Ethan Furman.
520
521
522
.. _whatsnew-pathlib:
523
524
pathlib
525
-------
526
527
The new :mod:`pathlib` module offers classes representing filesystem paths
528
with semantics appropriate for different operating systems. Path classes are
529
divided between *pure paths*, which provide purely computational operations
530
without I/O, and *concrete paths*, which inherit from pure paths but also
531
provide I/O operations.
532
533
For Python 3.4, this module is considered a :term:`provisional API`.
534
535
.. seealso::
536
537
:pep:`428` -- The pathlib module -- object-oriented filesystem paths
538
PEP written and implemented by Antoine Pitrou.
539
540
541
.. _whatsnew-selectors:
542
543
selectors
544
---------
545
546
The new :mod:`selectors` module (created as part of implementing :pep:`3156`)
547
allows high-level and efficient I/O multiplexing, built upon the
548
:mod:`select` module primitives.
549
550
551
.. _whatsnew-statistics:
552
553
statistics
554
----------
555
556
The new :mod:`statistics` module (defined in :pep:`450`) offers some core
557
statistics functionality directly in the standard library. This module
558
supports calculation of the mean, median, mode, variance and standard
559
deviation of a data series.
560
561
.. seealso::
562
563
:pep:`450` -- Adding A Statistics Module To The Standard Library
564
PEP written and implemented by Steven D'Aprano
565
566
.. _whatsnew-tracemalloc:
567
568
569
tracemalloc
570
-----------
571
572
The new :mod:`tracemalloc` module (defined in :pep:`454`) is a debug tool to
573
trace memory blocks allocated by Python. It provides the following information:
574
575
* Trace where an object was allocated
576
* Statistics on allocated memory blocks per filename and per line number:
577
total size, number and average size of allocated memory blocks
578
* Compute the differences between two snapshots to detect memory leaks
579
580
.. seealso::
581
582
:pep:`454` -- Add a new tracemalloc module to trace Python memory allocations
583
PEP written and implemented by Victor Stinner
584
585
586
587
Improved Modules
588
================
589
590
591
abc
592
---
593
594
New function :func:`abc.get_cache_token` can be used to know when to invalidate
595
caches that are affected by changes in the object graph. (Contributed
596
by Łukasz Langa in :issue:`16832`.)
597
598
New class :class:`~abc.ABC` has :class:`~abc.ABCMeta` as its meta class.
599
Using ``ABC`` as a base class has essentially the same effect as specifying
600
``metaclass=abc.ABCMeta``, but is simpler to type and easier to read.
601
(Contributed by Bruno Dupuis in :issue:`16049`.)
602
603
604
aifc
605
----
606
607
The :meth:`!getparams` method now returns a namedtuple rather than a
608
plain tuple. (Contributed by Claudiu Popa in :issue:`17818`.)
609
610
:func:`!aifc.open` now supports the context management protocol: when used in a
611
:keyword:`with` block, the :meth:`!close` method of the returned
612
object will be called automatically at the end of the block. (Contributed by
613
Serhiy Storchacha in :issue:`16486`.)
614
615
The :meth:`!writeframesraw` and :meth:`!writeframes`
616
methods now accept any :term:`bytes-like object`. (Contributed by Serhiy
617
Storchaka in :issue:`8311`.)
618
619
620
argparse
621
--------
622
623
The :class:`~argparse.FileType` class now accepts *encoding* and
624
*errors* arguments, which are passed through to :func:`open`. (Contributed
625
by Lucas Maystre in :issue:`11175`.)
626
627
628
audioop
629
-------
630
631
:mod:`!audioop` now supports 24-bit samples. (Contributed by Serhiy Storchaka
632
in :issue:`12866`.)
633
634
New :func:`!byteswap` function converts big-endian samples to
635
little-endian and vice versa. (Contributed by Serhiy Storchaka in
636
:issue:`19641`.)
637
638
All :mod:`!audioop` functions now accept any :term:`bytes-like object`. Strings
639
are not accepted: they didn't work before, now they raise an error right away.
640
(Contributed by Serhiy Storchaka in :issue:`16685`.)
641
642
643
base64
644
------
645
646
The encoding and decoding functions in :mod:`base64` now accept any
647
:term:`bytes-like object` in cases where it previously required a
648
:class:`bytes` or :class:`bytearray` instance. (Contributed by Nick Coghlan in
649
:issue:`17839`.)
650
651
New functions :func:`~base64.a85encode`, :func:`~base64.a85decode`,
652
:func:`~base64.b85encode`, and :func:`~base64.b85decode` provide the ability to
653
encode and decode binary data from and to ``Ascii85`` and the git/mercurial
654
``Base85`` formats, respectively. The ``a85`` functions have options that can
655
be used to make them compatible with the variants of the ``Ascii85`` encoding,
656
including the Adobe variant. (Contributed by Martin Morrison, the Mercurial
657
project, Serhiy Storchaka, and Antoine Pitrou in :issue:`17618`.)
658
659
660
collections
661
-----------
662
663
The :meth:`.ChainMap.new_child` method now accepts an *m* argument specifying
664
the child map to add to the chain. This allows an existing mapping and/or a
665
custom mapping type to be used for the child. (Contributed by Vinay Sajip in
666
:issue:`16613`.)
667
668
669
colorsys
670
--------
671
672
The number of digits in the coefficients for the RGB --- YIQ conversions have
673
been expanded so that they match the FCC NTSC versions. The change in
674
results should be less than 1% and may better match results found elsewhere.
675
(Contributed by Brian Landers and Serhiy Storchaka in :issue:`14323`.)
676
677
678
contextlib
679
----------
680
681
The new :class:`contextlib.suppress` context manager helps to clarify the
682
intent of code that deliberately suppresses exceptions from a single
683
statement. (Contributed by Raymond Hettinger in :issue:`15806` and
684
Zero Piraeus in :issue:`19266`.)
685
686
The new :func:`contextlib.redirect_stdout` context manager makes it easier
687
for utility scripts to handle inflexible APIs that write their output to
688
:data:`sys.stdout` and don't provide any options to redirect it. Using the
689
context manager, the :data:`sys.stdout` output can be redirected to any
690
other stream or, in conjunction with :class:`io.StringIO`, to a string.
691
The latter can be especially useful, for example, to capture output
692
from a function that was written to implement a command line interface.
693
It is recommended only for utility scripts because it affects the
694
global state of :data:`sys.stdout`. (Contributed by Raymond Hettinger
695
in :issue:`15805`.)
696
697
The :mod:`contextlib` documentation has also been updated to include a
698
:ref:`discussion <single-use-reusable-and-reentrant-cms>` of the
699
differences between single use, reusable and reentrant context managers.
700
701
702
dbm
703
---
704
705
:func:`dbm.open` objects now support the context management protocol. When
706
used in a :keyword:`with` statement, the ``close`` method of the database
707
object will be called automatically at the end of the block. (Contributed by
708
Claudiu Popa and Nick Coghlan in :issue:`19282`.)
709
710
711
dis
712
---
713
714
Functions :func:`~dis.show_code`, :func:`~dis.dis`, :func:`~dis.distb`, and
715
:func:`~dis.disassemble` now accept a keyword-only *file* argument that
716
controls where they write their output.
717
718
The :mod:`dis` module is now built around an :class:`~dis.Instruction` class
719
that provides object oriented access to the details of each individual bytecode
720
operation.
721
722
A new method, :func:`~dis.get_instructions`, provides an iterator that emits
723
the Instruction stream for a given piece of Python code. Thus it is now
724
possible to write a program that inspects and manipulates a bytecode
725
object in ways different from those provided by the :mod:`~dis` module
726
itself. For example::
727
728
>>> import dis
729
>>> for instr in dis.get_instructions(lambda x: x + 1):
730
... print(instr.opname)
731
LOAD_FAST
732
LOAD_CONST
733
BINARY_ADD
734
RETURN_VALUE
735
736
The various display tools in the :mod:`dis` module have been rewritten to use
737
these new components.
738
739
In addition, a new application-friendly class :class:`~dis.Bytecode` provides
740
an object-oriented API for inspecting bytecode in both in human-readable form
741
and for iterating over instructions. The :class:`~dis.Bytecode` constructor
742
takes the same arguments that :func:`~dis.get_instructions` does (plus an
743
optional *current_offset*), and the resulting object can be iterated to produce
744
:class:`~dis.Instruction` objects. But it also has a :mod:`~dis.Bytecode.dis`
745
method, equivalent to calling :mod:`~dis.dis` on the constructor argument, but
746
returned as a multi-line string::
747
748
>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
749
>>> for instr in bytecode:
750
... print('{} ({})'.format(instr.opname, instr.opcode))
751
LOAD_FAST (124)
752
LOAD_CONST (100)
753
BINARY_ADD (23)
754
RETURN_VALUE (83)
755
>>> bytecode.dis().splitlines() # doctest: +NORMALIZE_WHITESPACE
756
[' 1 0 LOAD_FAST 0 (x)',
757
' --> 3 LOAD_CONST 1 (1)',
758
' 6 BINARY_ADD',
759
' 7 RETURN_VALUE']
760
761
:class:`~dis.Bytecode` also has a class method,
762
:meth:`~dis.Bytecode.from_traceback`, that provides the ability to manipulate a
763
traceback (that is, ``print(Bytecode.from_traceback(tb).dis())`` is equivalent
764
to ``distb(tb)``).
765
766
(Contributed by Nick Coghlan, Ryan Kelly and Thomas Kluyver in :issue:`11816`
767
and Claudiu Popa in :issue:`17916`.)
768
769
New function :func:`~dis.stack_effect` computes the effect on the Python stack
770
of a given opcode and argument, information that is not otherwise available.
771
(Contributed by Larry Hastings in :issue:`19722`.)
772
773
774
doctest
775
-------
776
777
A new :ref:`option flag <doctest-options>`, :const:`~doctest.FAIL_FAST`, halts
778
test running as soon as the first failure is detected. (Contributed by R.
779
David Murray and Daniel Urban in :issue:`16522`.)
780
781
The :mod:`doctest` command line interface now uses :mod:`argparse`, and has two
782
new options, ``-o`` and ``-f``. ``-o`` allows :ref:`doctest options
783
<doctest-options>` to be specified on the command line, and ``-f`` is a
784
shorthand for ``-o FAIL_FAST`` (to parallel the similar option supported by the
785
:mod:`unittest` CLI). (Contributed by R. David Murray in :issue:`11390`.)
786
787
:mod:`doctest` will now find doctests in extension module ``__doc__`` strings.
788
(Contributed by Zachary Ware in :issue:`3158`.)
789
790
791
email
792
-----
793
794
:meth:`~email.message.Message.as_string` now accepts a *policy* argument to
795
override the default policy of the message when generating a string
796
representation of it. This means that ``as_string`` can now be used in more
797
circumstances, instead of having to create and use a :mod:`~email.generator` in
798
order to pass formatting parameters to its ``flatten`` method. (Contributed by
799
R. David Murray in :issue:`18600`.)
800
801
New method :meth:`~email.message.Message.as_bytes` added to produce a bytes
802
representation of the message in a fashion similar to how ``as_string``
803
produces a string representation. It does not accept the *maxheaderlen*
804
argument, but does accept the *unixfrom* and *policy* arguments. The
805
:class:`~email.message.Message` :meth:`~email.message.Message.__bytes__` method
806
calls it, meaning that ``bytes(mymsg)`` will now produce the intuitive
807
result: a bytes object containing the fully formatted message. (Contributed
808
by R. David Murray in :issue:`18600`.)
809
810
The :meth:`.Message.set_param` message now accepts a *replace* keyword argument.
811
When specified, the associated header will be updated without changing
812
its location in the list of headers. For backward compatibility, the default
813
is ``False``. (Contributed by R. David Murray in :issue:`18891`.)
814
815
816
.. _whatsnew_email_contentmanager:
817
818
A pair of new subclasses of :class:`~email.message.Message` have been added
819
(:class:`.EmailMessage` and :class:`.MIMEPart`), along with a new sub-module,
820
:mod:`~email.contentmanager` and a new :mod:`~email.policy` attribute
821
:attr:`~email.policy.EmailPolicy.content_manager`. All documentation is
822
currently in the new module, which is being added as part of email's new
823
:term:`provisional API`. These classes provide a number of new methods that
824
make extracting content from and inserting content into email messages much
825
easier. For details, see the :mod:`~email.contentmanager` documentation and
826
the :ref:`email-examples`. These API additions complete the
827
bulk of the work that was planned as part of the email6 project. The currently
828
provisional API is scheduled to become final in Python 3.5 (possibly with a few
829
minor additions in the area of error handling). (Contributed by R. David
830
Murray in :issue:`18891`.)
831
832
833
filecmp
834
-------
835
836
A new :func:`~filecmp.clear_cache` function provides the ability to clear the
837
:mod:`filecmp` comparison cache, which uses :func:`os.stat` information to
838
determine if the file has changed since the last compare. This can be used,
839
for example, if the file might have been changed and re-checked in less time
840
than the resolution of a particular filesystem's file modification time field.
841
(Contributed by Mark Levitt in :issue:`18149`.)
842
843
New module attribute :const:`~filecmp.DEFAULT_IGNORES` provides the list of
844
directories that are used as the default value for the *ignore* parameter of
845
the :func:`~filecmp.dircmp` function. (Contributed by Eli Bendersky in
846
:issue:`15442`.)
847
848
849
functools
850
---------
851
852
The new :func:`~functools.partialmethod` descriptor brings partial argument
853
application to descriptors, just as :func:`~functools.partial` provides
854
for normal callables. The new descriptor also makes it easier to get
855
arbitrary callables (including :func:`~functools.partial` instances)
856
to behave like normal instance methods when included in a class definition.
857
(Contributed by Alon Horev and Nick Coghlan in :issue:`4331`.)
858
859
.. _whatsnew-singledispatch:
860
861
The new :func:`~functools.singledispatch` decorator brings support for
862
single-dispatch generic functions to the Python standard library. Where
863
object oriented programming focuses on grouping multiple operations on a
864
common set of data into a class, a generic function focuses on grouping
865
multiple implementations of an operation that allows it to work with
866
*different* kinds of data.
867
868
.. seealso::
869
870
:pep:`443` -- Single-dispatch generic functions
871
PEP written and implemented by Łukasz Langa.
872
873
:func:`~functools.total_ordering` now supports a return value of
874
:data:`NotImplemented` from the underlying comparison function. (Contributed
875
by Katie Miller in :issue:`10042`.)
876
877
A pure-python version of the :func:`~functools.partial` function is now in the
878
stdlib; in CPython it is overridden by the C accelerated version, but it is
879
available for other implementations to use. (Contributed by Brian Thorne in
880
:issue:`12428`.)
881
882
883
gc
884
--
885
886
New function :func:`~gc.get_stats` returns a list of three per-generation
887
dictionaries containing the collections statistics since interpreter startup.
888
(Contributed by Antoine Pitrou in :issue:`16351`.)
889
890
891
glob
892
----
893
894
A new function :func:`~glob.escape` provides a way to escape special characters
895
in a filename so that they do not become part of the globbing expansion but are
896
instead matched literally. (Contributed by Serhiy Storchaka in :issue:`8402`.)
897
898
899
hashlib
900
-------
901
902
A new :func:`hashlib.pbkdf2_hmac` function provides
903
the `PKCS#5 password-based key derivation function 2
904
<https://en.wikipedia.org/wiki/PBKDF2>`_. (Contributed by Christian
905
Heimes in :issue:`18582`.)
906
907
The :attr:`~hashlib.hash.name` attribute of :mod:`hashlib` hash objects is now
908
a formally supported interface. It has always existed in CPython's
909
:mod:`hashlib` (although it did not return lower case names for all supported
910
hashes), but it was not a public interface and so some other Python
911
implementations have not previously supported it. (Contributed by Jason R.
912
Coombs in :issue:`18532`.)
913
914
915
hmac
916
----
917
918
:mod:`hmac` now accepts ``bytearray`` as well as ``bytes`` for the *key*
919
argument to the :func:`~hmac.new` function, and the *msg* parameter to both the
920
:func:`~hmac.new` function and the :meth:`~hmac.HMAC.update` method now
921
accepts any type supported by the :mod:`hashlib` module. (Contributed
922
by Jonas Borgström in :issue:`18240`.)
923
924
The *digestmod* argument to the :func:`hmac.new` function may now be any hash
925
digest name recognized by :mod:`hashlib`. In addition, the current behavior in
926
which the value of *digestmod* defaults to ``MD5`` is deprecated: in a
927
future version of Python there will be no default value. (Contributed by
928
Christian Heimes in :issue:`17276`.)
929
930
With the addition of :attr:`~hmac.HMAC.block_size` and :attr:`~hmac.HMAC.name`
931
attributes (and the formal documentation of the :attr:`~hmac.HMAC.digest_size`
932
attribute), the :mod:`hmac` module now conforms fully to the :pep:`247` API.
933
(Contributed by Christian Heimes in :issue:`18775`.)
934
935
936
html
937
----
938
939
New function :func:`~html.unescape` function converts HTML5 character references to
940
the corresponding Unicode characters. (Contributed by Ezio Melotti in
941
:issue:`2927`.)
942
943
:class:`~html.parser.HTMLParser` accepts a new keyword argument
944
*convert_charrefs* that, when ``True``, automatically converts all character
945
references. For backward-compatibility, its value defaults to ``False``, but
946
it will change to ``True`` in a future version of Python, so you are invited to
947
set it explicitly and update your code to use this new feature. (Contributed
948
by Ezio Melotti in :issue:`13633`.)
949
950
The *strict* argument of :class:`~html.parser.HTMLParser` is now deprecated.
951
(Contributed by Ezio Melotti in :issue:`15114`.)
952
953
954
http
955
----
956
957
:meth:`~http.server.BaseHTTPRequestHandler.send_error` now accepts an
958
optional additional *explain* parameter which can be used to provide an
959
extended error description, overriding the hardcoded default if there is one.
960
This extended error description will be formatted using the
961
:attr:`~http.server.BaseHTTPRequestHandler.error_message_format` attribute
962
and sent as the body of the error response.
963
(Contributed by Karl Cow in :issue:`12921`.)
964
965
The :mod:`http.server` :ref:`command line interface <http-server-cli>` now has
966
a ``-b/--bind`` option that causes the server to listen on a specific address.
967
(Contributed by Malte Swart in :issue:`17764`.)
968
969
970
idlelib and IDLE
971
----------------
972
973
Since idlelib implements the IDLE shell and editor and is not intended for
974
import by other programs, it gets improvements with every release. See
975
:file:`Lib/idlelib/NEWS.txt` for a cumulative list of changes since 3.3.0,
976
as well as changes made in future 3.4.x releases. This file is also available
977
from the IDLE :menuselection:`Help --> About IDLE` dialog.
978
979
980
importlib
981
---------
982
983
The :class:`~importlib.abc.InspectLoader` ABC defines a new method,
984
:meth:`~importlib.abc.InspectLoader.source_to_code` that accepts source
985
data and a path and returns a code object. The default implementation
986
is equivalent to ``compile(data, path, 'exec', dont_inherit=True)``.
987
(Contributed by Eric Snow and Brett Cannon in :issue:`15627`.)
988
989
:class:`~importlib.abc.InspectLoader` also now has a default implementation
990
for the :meth:`~importlib.abc.InspectLoader.get_code` method. However,
991
it will normally be desirable to override the default implementation
992
for performance reasons. (Contributed by Brett Cannon in :issue:`18072`.)
993
994
The :func:`~importlib.reload` function has been moved from :mod:`!imp` to
995
:mod:`importlib` as part of the :mod:`!imp` module deprecation. (Contributed by
996
Berker Peksag in :issue:`18193`.)
997
998
:mod:`importlib.util` now has a :const:`~importlib.util.MAGIC_NUMBER` attribute
999
providing access to the bytecode version number. This replaces the
1000
:func:`!get_magic` function in the deprecated :mod:`!imp` module.