blob: fef712d2ab2960cf47c16602715a1b129edb4c16 [file] [log] [blame]
Ned Deily07a18922018-01-31 18:12:38 -05001****************************
2 What's New In Python 3.8
3****************************
4
Ned Deily07a18922018-01-31 18:12:38 -05005.. Rules for maintenance:
6
7 * Anyone can add text to this document. Do not spend very much time
8 on the wording of your changes, because your text will probably
9 get rewritten to some degree.
10
11 * The maintainer will go through Misc/NEWS periodically and add
12 changes; it's therefore more important to add your changes to
13 Misc/NEWS than to this file.
14
15 * This is not a complete list of every single change; completeness
16 is the purpose of Misc/NEWS. Some changes I consider too small
17 or esoteric to include. If such a change is added to the text,
18 I'll just remove it. (This is another reason you shouldn't spend
19 too much time on writing your addition.)
20
21 * If you want to draw your new text to the attention of the
22 maintainer, add 'XXX' to the beginning of the paragraph or
23 section.
24
25 * It's OK to just add a fragmentary note about a change. For
26 example: "XXX Describe the transmogrify() function added to the
27 socket module." The maintainer will research the change and
28 write the necessary text.
29
30 * You can comment out your additions if you like, but it's not
31 necessary (especially when a final release is some months away).
32
33 * Credit the author of a patch or bugfix. Just the name is
34 sufficient; the e-mail address isn't necessary.
35
36 * It's helpful to add the bug/patch number as a comment:
37
38 XXX Describe the transmogrify() function added to the socket
39 module.
40 (Contributed by P.Y. Developer in :issue:`12345`.)
41
Raymond Hettinger66a34d32019-08-12 15:55:18 -070042 This saves the maintainer the effort of going through the Git log
Ned Deily07a18922018-01-31 18:12:38 -050043 when researching a change.
44
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070045:Editor: Raymond Hettinger
Ned Deily07a18922018-01-31 18:12:38 -050046
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070047This article explains the new features in Python 3.8, compared to 3.7.
Ned Deily45ab51c2018-02-28 13:58:38 -050048For full details, see the :ref:`changelog <changelog>`.
Ned Deily07a18922018-01-31 18:12:38 -050049
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070050.. testsetup::
Nick Coghlanb9438ce2019-06-09 19:07:42 +100051
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070052 from datetime import date
53 from math import cos, radians
Raymond Hettinger66a34d32019-08-12 15:55:18 -070054 from unicodedata import normalize
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070055 import re
56 import math
Nick Coghlanb9438ce2019-06-09 19:07:42 +100057
Ned Deily07a18922018-01-31 18:12:38 -050058
59Summary -- Release highlights
60=============================
61
62.. This section singles out the most important changes in Python 3.8.
63 Brevity is key.
64
65
66.. PEP-sized items next.
67
68
69
70New Features
71============
72
Guido van Rossum09d434c2019-04-24 11:30:17 -070073Assignment expressions
74----------------------
75
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070076There is new syntax ``:=`` that assigns values to variables as part of a larger
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -040077expression. It is affectionately known as "the walrus operator" due to
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070078its resemblance to `the eyes and tusks of a walrus
79<https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg>`_.
80
81In this example, the assignment expression helps avoid calling
82:func:`len` twice::
Guido van Rossum09d434c2019-04-24 11:30:17 -070083
84 if (n := len(a)) > 10:
85 print(f"List is too long ({n} elements, expected <= 10)")
86
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -070087A similar benefit arises during regular expression matching where
88match objects are needed twice, once to test whether a match
89occurred and another to extract a subgroup::
90
91 discount = 0.0
92 if (mo := re.search(r'(\d+)% discount', advertisement)):
93 discount = float(mo.group(1)) / 100.0
94
95The operator is also useful with while-loops that compute
96a value to test loop termination and then need that same
97value again in the body of the loop::
98
99 # Loop over fixed length blocks
100 while (block := f.read(256)) != '':
101 process(block)
102
103Another motivating use case arises in list comprehensions where
104a value computed in a filtering condition is also needed in
105the expression body::
106
107 [clean_name.title() for name in names
108 if (clean_name := normalize('NFC', name)) in allowed_names]
109
110Try to limit use of the walrus operator to clean cases that reduce
111complexity and improve readability.
112
Guido van Rossum09d434c2019-04-24 11:30:17 -0700113See :pep:`572` for a full description.
114
115(Contributed by Emily Morehouse in :issue:`35224`.)
116
Guido van Rossum09d434c2019-04-24 11:30:17 -0700117
Guido van Rossum843bf422019-04-29 05:49:30 -0700118Positional-only parameters
119--------------------------
120
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700121There is a new function parameter syntax ``/`` to indicate that some
122function parameters must be specified positionally and cannot be used as
123keyword arguments. This is the same notation shown by ``help()`` for C
124functions annotated with Larry Hastings' `Argument Clinic
125<https://docs.python.org/3/howto/clinic.html>`_ tool.
126
127In the following example, parameters *a* and *b* are positional-only,
128while *c* or *d* can be positional or keyword, and *e* or *f* are
129required to be keywords::
130
131 def f(a, b, /, c, d, *, e, f):
132 print(a, b, c, d, e, f)
133
134The following is a valid call::
135
136 f(10, 20, 30, d=40, e=50, f=60)
137
138However, these are invalid calls::
139
140 f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
141 f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument
142
143One use case for this notation is that it allows pure Python functions
144to fully emulate behaviors of existing C coded functions. For example,
145the built-in :func:`pow` function does not accept keyword arguments::
Guido van Rossum843bf422019-04-29 05:49:30 -0700146
147 def pow(x, y, z=None, /):
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700148 "Emulate the built in pow() function"
149 r = x ** y
150 return r if z is None else r%z
Guido van Rossum843bf422019-04-29 05:49:30 -0700151
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700152Another use case is to preclude keyword arguments when the parameter
153name is not helpful. For example, the builtin :func:`len` function has
154the signature ``len(obj, /)``. This precludes awkward calls such as::
155
156 len(obj='hello') # The "obj" keyword argument impairs readability
157
158A further benefit of marking a parameter as positional-only is that it
159allows the parameter name to be changed in the future without risk of
160breaking client code. For example, in the :mod:`statistics` module, the
161parameter name *dist* may be changed in the future. This was made
162possible with the following function specification::
163
164 def quantiles(dist, /, *, n=4, method='exclusive')
165 ...
166
167Since the parameters to the left of ``/`` are not exposed as possible
168keywords, the parameters names remain available for use in ``**kwargs``::
169
170 >>> def f(a, b, /, **kwargs):
171 ... print(a, b, kwargs)
172 ...
173 >>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
174 10 20 {'a': 1, 'b': 2, 'c': 3}
175
176This greatly simplifies the implementation of functions and methods
177that need to accept arbitrary keyword arguments. For example, here
Hugo van Kemenade547c60c2019-10-12 20:53:36 +0300178is an excerpt from code in the :mod:`collections` module::
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700179
180 class Counter(dict):
181
182 def __init__(self, iterable=None, /, **kwds):
183 # Note "iterable" is a possible keyword argument
Guido van Rossum843bf422019-04-29 05:49:30 -0700184
185See :pep:`570` for a full description.
186
187(Contributed by Pablo Galindo in :issue:`36540`.)
188
189.. TODO: Pablo will sprint on docs at PyCon US 2019.
190
191
Nick Coghlan16eb3bc2018-06-20 21:25:01 +1000192Parallel filesystem cache for compiled bytecode files
193-----------------------------------------------------
194
195The new :envvar:`PYTHONPYCACHEPREFIX` setting (also available as
196:option:`-X` ``pycache_prefix``) configures the implicit bytecode
197cache to use a separate parallel filesystem tree, rather than
198the default ``__pycache__`` subdirectories within each source
199directory.
200
201The location of the cache is reported in :data:`sys.pycache_prefix`
202(:const:`None` indicates the default location in ``__pycache__``
203subdirectories).
204
205(Contributed by Carl Meyer in :issue:`33499`.)
Ned Deily07a18922018-01-31 18:12:38 -0500206
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300207
Victor Stinner40460692019-04-26 17:56:44 +0200208Debug build uses the same ABI as release build
209-----------------------------------------------
210
Hugo van Kemenade547c60c2019-10-12 20:53:36 +0300211Python now uses the same ABI whether it's built in release or debug mode. On
Paul Ganssle5c403b22019-04-27 14:14:35 -0400212Unix, when Python is built in debug mode, it is now possible to load C
213extensions built in release mode and C extensions built using the stable ABI.
Victor Stinner40460692019-04-26 17:56:44 +0200214
Paul Ganssle5c403b22019-04-27 14:14:35 -0400215Release builds and debug builds are now ABI compatible: defining the
216``Py_DEBUG`` macro no longer implies the ``Py_TRACE_REFS`` macro, which
217introduces the only ABI incompatibility. The ``Py_TRACE_REFS`` macro, which
218adds the :func:`sys.getobjects` function and the :envvar:`PYTHONDUMPREFS`
219environment variable, can be set using the new ``./configure --with-trace-refs``
220build option.
Victor Stinner40460692019-04-26 17:56:44 +0200221(Contributed by Victor Stinner in :issue:`36465`.)
222
E. M. Brayc994c8f2019-05-24 17:33:47 +0200223On Unix, C extensions are no longer linked to libpython except on Android
224and Cygwin.
Victor Stinner4ebcd7e2019-05-11 04:10:03 +0200225It is now possible
Paul Ganssle5c403b22019-04-27 14:14:35 -0400226for a statically linked Python to load a C extension built using a shared
227library Python.
Victor Stinner40460692019-04-26 17:56:44 +0200228(Contributed by Victor Stinner in :issue:`21536`.)
229
230On Unix, when Python is built in debug mode, import now also looks for C
231extensions compiled in release mode and for C extensions compiled with the
232stable ABI.
233(Contributed by Victor Stinner in :issue:`36722`.)
234
Victor Stinner0a8e5722019-05-23 03:30:23 +0200235To embed Python into an application, a new ``--embed`` option must be passed to
236``python3-config --libs --embed`` to get ``-lpython3.8`` (link the application
237to libpython). To support both 3.8 and older, try ``python3-config --libs
238--embed`` first and fallback to ``python3-config --libs`` (without ``--embed``)
239if the previous command fails.
240
241Add a pkg-config ``python-3.8-embed`` module to embed Python into an
242application: ``pkg-config python-3.8-embed --libs`` includes ``-lpython3.8``.
243To support both 3.8 and older, try ``pkg-config python-X.Y-embed --libs`` first
244and fallback to ``pkg-config python-X.Y --libs`` (without ``--embed``) if the
245previous command fails (replace ``X.Y`` with the Python version).
246
247On the other hand, ``pkg-config python3.8 --libs`` no longer contains
248``-lpython3.8``. C extensions must not be linked to libpython (except on
E. M. Brayc994c8f2019-05-24 17:33:47 +0200249Android and Cygwin, whose cases are handled by the script);
250this change is backward incompatible on purpose.
Victor Stinner0a8e5722019-05-23 03:30:23 +0200251(Contributed by Victor Stinner in :issue:`36721`.)
252
Eric V. Smith9a4135e2019-05-08 16:28:48 -0400253
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700254f-strings support ``=`` for self-documenting expressions and debugging
255----------------------------------------------------------------------
Eric V. Smith9a4135e2019-05-08 16:28:48 -0400256
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700257Added an ``=`` specifier to :term:`f-string`\s. An f-string such as
258``f'{expr=}'`` will expand to the text of the expression, an equal sign,
259then the representation of the evaluated expression. For example:
Eric V. Smith9a4135e2019-05-08 16:28:48 -0400260
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700261 >>> user = 'eric_idle'
262 >>> member_since = date(1975, 7, 31)
263 >>> f'{user=} {member_since=}'
264 "user='eric_idle' member_since=datetime.date(1975, 7, 31)"
265
266The usual :ref:`f-string format specifiers <f-strings>` allow more
267control over how the result of the expression is displayed::
268
269 >>> delta = date.today() - member_since
270 >>> f'{user=!s} {delta.days=:,d}'
271 'user=eric_idle delta.days=16,075'
272
273The ``=`` specifier will display the whole expression so that
274calculations can be shown::
275
276 >>> print(f'{theta=} {cos(radians(theta))=:.3f}')
277 theta=30 cos(radians(theta))=0.866
Eric V. Smith9a4135e2019-05-08 16:28:48 -0400278
279(Contributed by Eric V. Smith and Larry Hastings in :issue:`36817`.)
280
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300281
Raymond Hettinger274bd012019-10-14 09:01:05 -0700282PEP 578: Python Runtime Audit Hooks
283-----------------------------------
284
285The PEP adds an Audit Hook and Verified Open Hook. Both are available from
286Python and native code, allowing applications and frameworks written in pure
287Python code to take advantage of extra notifications, while also allowing
288embedders or system administrators to deploy builds of Python where auditing is
289always enabled.
290
291See :pep:`578` for full details.
292
293
Victor Stinner331a6a52019-05-27 16:39:22 +0200294PEP 587: Python Initialization Configuration
295--------------------------------------------
296
297The :pep:`587` adds a new C API to configure the Python Initialization
298providing finer control on the whole configuration and better error reporting.
299
300New structures:
301
302* :c:type:`PyConfig`
303* :c:type:`PyPreConfig`
304* :c:type:`PyStatus`
305* :c:type:`PyWideStringList`
306
307New functions:
308
309* :c:func:`PyConfig_Clear`
310* :c:func:`PyConfig_InitIsolatedConfig`
311* :c:func:`PyConfig_InitPythonConfig`
312* :c:func:`PyConfig_Read`
313* :c:func:`PyConfig_SetArgv`
314* :c:func:`PyConfig_SetBytesArgv`
315* :c:func:`PyConfig_SetBytesString`
316* :c:func:`PyConfig_SetString`
317* :c:func:`PyPreConfig_InitIsolatedConfig`
318* :c:func:`PyPreConfig_InitPythonConfig`
319* :c:func:`PyStatus_Error`
320* :c:func:`PyStatus_Exception`
321* :c:func:`PyStatus_Exit`
322* :c:func:`PyStatus_IsError`
323* :c:func:`PyStatus_IsExit`
324* :c:func:`PyStatus_NoMemory`
325* :c:func:`PyStatus_Ok`
326* :c:func:`PyWideStringList_Append`
327* :c:func:`PyWideStringList_Insert`
328* :c:func:`Py_BytesMain`
329* :c:func:`Py_ExitStatusException`
330* :c:func:`Py_InitializeFromConfig`
331* :c:func:`Py_PreInitialize`
332* :c:func:`Py_PreInitializeFromArgs`
333* :c:func:`Py_PreInitializeFromBytesArgs`
334* :c:func:`Py_RunMain`
335
336This PEP also adds ``_PyRuntimeState.preconfig`` (:c:type:`PyPreConfig` type)
337and ``PyInterpreterState.config`` (:c:type:`PyConfig` type) fields to these
338internal structures. ``PyInterpreterState.config`` becomes the new
339reference configuration, replacing global configuration variables and
340other private variables.
341
342See :ref:`Python Initialization Configuration <init-config>` for the
343documentation.
344
345See :pep:`587` for a full description.
346
347(Contributed by Victor Stinner in :issue:`36763`.)
348
Ned Deily07a18922018-01-31 18:12:38 -0500349
Jeroen Demeyer9e3e06e2019-06-03 01:43:13 +0200350Vectorcall: a fast calling protocol for CPython
351-----------------------------------------------
352
353The "vectorcall" protocol is added to the Python/C API.
354It is meant to formalize existing optimizations which were already done
355for various classes.
356Any extension type implementing a callable can use this protocol.
357
358This is currently provisional,
359the aim is to make it fully public in Python 3.9.
360
361See :pep:`590` for a full description.
362
363(Contributed by Jeroen Demeyer and Mark Shannon in :issue:`36974`.)
364
365
Antoine Pitrouc879ff22019-06-09 14:47:15 +0200366Pickle protocol 5 with out-of-band data buffers
367-----------------------------------------------
368
369When :mod:`pickle` is used to transfer large data between Python processes
370in order to take advantage of multi-core or multi-machine processing,
371it is important to optimize the transfer by reducing memory copies, and
372possibly by applying custom techniques such as data-dependent compression.
373
374The :mod:`pickle` protocol 5 introduces support for out-of-band buffers
375where :pep:`3118`-compatible data can be transmitted separately from the
376main pickle stream, at the discretion of the communication layer.
377
378See :pep:`574` for a full description.
379
380(Contributed by Antoine Pitrou in :issue:`36785`.)
381
382
Ned Deily07a18922018-01-31 18:12:38 -0500383Other Language Changes
384======================
385
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200386* A :keyword:`continue` statement was illegal in the :keyword:`finally` clause
387 due to a problem with the implementation. In Python 3.8 this restriction
388 was lifted.
389 (Contributed by Serhiy Storchaka in :issue:`32489`.)
390
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700391* The :class:`bool`, :class:`int`, and :class:`fractions.Fraction` types
392 now have an :meth:`~int.as_integer_ratio` method like that found in
393 :class:`float` and :class:`decimal.Decimal`. This minor API extension
394 makes it possible to write ``numerator, denominator =
395 x.as_integer_ratio()`` and have it work across multiple numeric types.
396 (Contributed by Lisa Roach in :issue:`33073` and Raymond Hettinger in
397 :issue:`37819`.)
Lisa Roach5ac70432018-09-13 23:56:23 -0700398
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300399* Constructors of :class:`int`, :class:`float` and :class:`complex` will now
400 use the :meth:`~object.__index__` special method, if available and the
401 corresponding method :meth:`~object.__int__`, :meth:`~object.__float__`
402 or :meth:`~object.__complex__` is not available.
403 (Contributed by Serhiy Storchaka in :issue:`20092`.)
404
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700405* Added support of ``\N{name}`` escapes in :mod:`regular expressions <re>`::
406
407 >>> notice = 'Copyright © 2019'
408 >>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})')
409 >>> int(copyright_year_pattern.search(notice).group(1))
410 2019
411
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200412 (Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.)
Ned Deily07a18922018-01-31 18:12:38 -0500413
Rémi Lapeyre6531bf62018-11-06 01:38:54 +0100414* Dict and dictviews are now iterable in reversed insertion order using
415 :func:`reversed`. (Contributed by Rémi Lapeyre in :issue:`33462`.)
416
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -0700417* The syntax allowed for keyword names in function calls was further
418 restricted. In particular, ``f((keyword)=arg)`` is no longer allowed. It was
419 never intended to permit more than a bare name on the left-hand side of a
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300420 keyword argument assignment term.
421 (Contributed by Benjamin Peterson in :issue:`34641`.)
Ned Deily07a18922018-01-31 18:12:38 -0500422
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700423* Generalized iterable unpacking in :keyword:`yield` and
424 :keyword:`return` statements no longer requires enclosing parentheses.
425 This brings the *yield* and *return* syntax into better agreement with
426 normal assignment syntax::
427
428 >>> def parse(family):
429 lastname, *members = family.split()
430 return lastname.upper(), *members
431
432 >>> parse('simpsons homer marge bart lisa sally')
433 ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'sally')
434
jChapman8fabae32018-09-22 21:13:10 -0400435 (Contributed by David Cuthbert and Jordan Chapman in :issue:`32117`.)
436
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700437* When a comma is missed in code such as ``[(10, 20) (30, 40)]``, the
438 compiler displays a :exc:`SyntaxWarning` with a helpful suggestion.
439 This improves on just having a :exc:`TypeError` indicating that the
440 first tuple was not callable. (Contributed by Serhiy Storchaka in
441 :issue:`15248`.)
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200442
Paul Ganssled9503c32019-02-08 11:02:00 -0500443* Arithmetic operations between subclasses of :class:`datetime.date` or
444 :class:`datetime.datetime` and :class:`datetime.timedelta` objects now return
445 an instance of the subclass, rather than the base class. This also affects
446 the return type of operations whose implementation (directly or indirectly)
447 uses :class:`datetime.timedelta` arithmetic, such as
448 :meth:`datetime.datetime.astimezone`.
449 (Contributed by Paul Ganssle in :issue:`32417`.)
450
Gregory P. Smith06babb22019-02-23 10:43:49 -0800451* When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the
452 resulting :exc:`KeyboardInterrupt` exception is not caught, the Python process
453 now exits via a SIGINT signal or with the correct exit code such that the
454 calling process can detect that it died due to a Ctrl-C. Shells on POSIX
455 and Windows use this to properly terminate scripts in interactive sessions.
456 (Contributed by Google via Gregory P. Smith in :issue:`1054041`.)
457
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700458* Some advanced styles of programming require updating the
459 :class:`types.CodeType` object for an existing function. Since code
460 objects are immutable, a new code object needs to be created, one
461 that is modeled on the existing code object. With 19 parameters,
462 this was somewhat tedious. Now, the new ``replace()`` method makes
463 it possible to create a clone with a few altered parameters.
464
465 Here's an example that alters the :func:`statistics.mean` function to
466 prevent the *data* parameter from being used as a keyword argument::
467
468 >>> from statistics import mean
469 >>> mean(data=[10, 20, 90])
470 40
471 >>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
472 >>> mean(data=[10, 20, 90])
473 Traceback (most recent call last):
474 ...
475 TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'
476
Victor Stinnera9f05d62019-05-24 23:57:23 +0200477 (Contributed by Victor Stinner in :issue:`37032`.)
478
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700479* For integers, the three-argument form of the :func:`pow` function now
480 permits the exponent to be negative in the case where the base is
481 relatively prime to the modulus. It then computes a modular inverse to
482 the base when the exponent is ``-1``, and a suitable power of that
483 inverse for other negative exponents. For example, to compute the
484 `modular multiplicative inverse
485 <https://en.wikipedia.org/wiki/Modular_multiplicative_inverse>`_ of 38
486 modulo 137, write::
487
488 >>> pow(38, -1, 137)
489 119
490 >>> 119 * 38 % 137
491 1
492
493 Modular inverses arise in the solution of `linear Diophantine
494 equations <https://en.wikipedia.org/wiki/Diophantine_equation>`_.
495 For example, to find integer solutions for ``4258𝑥 + 147𝑦 = 369``,
496 first rewrite as ``4258𝑥 ≡ 369 (mod 147)`` then solve:
497
498 >>> x = 369 * pow(4258, -1, 147) % 147
499 >>> y = (4258 * x - 369) // -147
500 >>> 4258 * x + 147 * y
501 369
502
Mark Dickinsonc5299672019-06-02 10:24:06 +0100503 (Contributed by Mark Dickinson in :issue:`36027`.)
504
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700505* Dict comprehensions have been synced-up with dict literals so that the
506 key is computed first and the value second::
507
508 >>> # Dict comprehension
509 >>> cast = {input('role? '): input('actor? ') for i in range(2)}
510 role? King Arthur
511 actor? Chapman
512 role? Black Knight
513 actor? Cleese
514
515 >>> # Dict literal
516 >>> cast = {input('role? '): input('actor? ')}
517 role? Sir Robin
518 actor? Eric Idle
519
520 The guaranteed execution order is helpful with assignment expressions
521 because variables assigned in the key expression will be available in
522 the value expression::
523
524 >>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
525 >>> {(n := normalize('NFC', name)).casefold() : n for name in names}
526 {'martin von löwis': 'Martin von Löwis',
527 'łukasz langa': 'Łukasz Langa',
528 'walter dörwald': 'Walter Dörwald'}
Pablo Galindob51b7132019-06-25 02:41:58 +0100529
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300530 (Contributed by Jörn Heissler in :issue:`35224`.)
531
Serhiy Storchaka65439122018-10-19 17:42:06 +0300532
Ned Deily07a18922018-01-31 18:12:38 -0500533New Modules
534===========
535
Barry Warsaw4867eaa2019-06-05 19:40:19 -0700536* The new :mod:`importlib.metadata` module provides (provisional) support for
Raymond Hettinger66a34d32019-08-12 15:55:18 -0700537 reading metadata from third-party packages. For example, it can extract an
538 installed package's version number, list of entry points, and more::
539
540 >>> # Note following example requires that the popular "requests"
541 >>> # package has been installed.
542 >>>
543 >>> from importlib.metadata import version, requires, files
544 >>> version('requests')
545 '2.22.0'
546 >>> list(requires('requests'))
547 ['chardet (<3.1.0,>=3.0.2)']
548 >>> list(files('requests'))[:5]
549 [PackagePath('requests-2.22.0.dist-info/INSTALLER'),
550 PackagePath('requests-2.22.0.dist-info/LICENSE'),
551 PackagePath('requests-2.22.0.dist-info/METADATA'),
552 PackagePath('requests-2.22.0.dist-info/RECORD'),
553 PackagePath('requests-2.22.0.dist-info/WHEEL')]
554
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300555 (Contributed by Barry Warsaw and Jason R. Coombs in :issue:`34632`.)
Ned Deily07a18922018-01-31 18:12:38 -0500556
557
558Improved Modules
559================
560
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700561ast
562---
563
564AST nodes now have ``end_lineno`` and ``end_col_offset`` attributes,
565which give the precise location of the end of the node. (This only
566applies to nodes that have ``lineno`` and ``col_offset`` attributes.)
567
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300568New function :func:`ast.get_source_segment` returns the source code
569for a specific AST node.
570
571(Contributed by Ivan Levkivskyi in :issue:`33416`.)
572
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700573The :func:`ast.parse` function has some new flags:
574
575* ``type_comments=True`` causes it to return the text of :pep:`484` and
576 :pep:`526` type comments associated with certain AST nodes;
577
578* ``mode='func_type'`` can be used to parse :pep:`484` "signature type
579 comments" (returned for function definition AST nodes);
580
Guido van Rossum10b55c12019-06-11 17:23:12 -0700581* ``feature_version=(3, N)`` allows specifying an earlier Python 3
Hugo van Kemenade547c60c2019-10-12 20:53:36 +0300582 version. (For example, ``feature_version=(3, 4)`` will treat
Guido van Rossum10b55c12019-06-11 17:23:12 -0700583 ``async`` and ``await`` as non-reserved words.)
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700584
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300585(Contributed by Guido van Rossum in :issue:`35766`.)
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700586
587
Victor Stinner6ea29c52018-09-25 08:27:08 -0700588asyncio
589-------
590
Raymond Hettinger274bd012019-10-14 09:01:05 -0700591Running ``python -m asyncio`` launches a natively async REPL. This allows rapid
592experimentation with code that has a top-level :keyword:`await`. There is no
593longer a need to directly call ``asyncio.run()`` which would spawn a new event
594loop on every invocation:
595
596.. code-block:: none
597
598 $ python -m asyncio
599 asyncio REPL 3.8.0
600 Use "await" directly instead of "asyncio.run()".
601 Type "help", "copyright", "credits" or "license" for more information.
602 >>> import asyncio
603 >>> await asyncio.sleep(10, result='hello')
604 hello
605
606(Contributed by Yury Selivanov in :issue:`37028`.)
607
Victor Stinner6ea29c52018-09-25 08:27:08 -0700608On Windows, the default event loop is now :class:`~asyncio.ProactorEventLoop`.
Victor Stinner01ae8972019-06-03 16:28:01 +0200609(Contributed by Victor Stinner in :issue:`34687`.)
610
611:class:`~asyncio.ProactorEventLoop` now also supports UDP.
612(Contributed by Adam Meily and Andrew Svetlov in :issue:`29883`.)
613
614:class:`~asyncio.ProactorEventLoop` can now be interrupted by
615:exc:`KeyboardInterrupt` ("CTRL+C").
616(Contributed by Vladimir Matveev in :issue:`23057`.)
617
Victor Stinner6ea29c52018-09-25 08:27:08 -0700618
Matthias Bussonnier2ddbd212019-05-22 12:07:45 -0700619builtins
620--------
621
622The :func:`compile` built-in has been improved to accept the
623``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` flag. With this new flag passed,
624:func:`compile` will allow top-level ``await``, ``async for`` and ``async with``
625constructs that are usually considered invalid syntax. Asynchronous code object
626marked with the ``CO_COROUTINE`` flag may then be returned.
Matthias Bussonnier2ddbd212019-05-22 12:07:45 -0700627(Contributed by Matthias Bussonnier in :issue:`34616`)
Terry Jan Reedyfdcb5ae2018-09-25 12:45:27 -0400628
Raymond Hettinger61a6db52019-10-13 21:31:12 -0700629
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700630collections
631-----------
632
633The :meth:`_asdict()` method for :func:`collections.namedtuple` now returns
Daniel Porteous05222912019-05-02 04:20:59 -0400634a :class:`dict` instead of a :class:`collections.OrderedDict`. This works because
635regular dicts have guaranteed ordering since Python 3.7. If the extra
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700636features of :class:`OrderedDict` are required, the suggested remediation is
637to cast the result to the desired type: ``OrderedDict(nt._asdict())``.
638(Contributed by Raymond Hettinger in :issue:`35864`.)
639
640
Raymond Hettinger61a6db52019-10-13 21:31:12 -0700641curses
642-------
643
644Added a new variable holding structured version information for the
645underlying ncurses library: :data:`~curses.ncurses_version`.
646(Contributed by Serhiy Storchaka in :issue:`31680`.)
647
648
Steve Dower2438cdf2019-03-29 16:37:16 -0700649ctypes
650------
651
652On Windows, :class:`~ctypes.CDLL` and subclasses now accept a *winmode* parameter
653to specify flags for the underlying ``LoadLibraryEx`` call. The default flags are
654set to only load DLL dependencies from trusted locations, including the path
655where the DLL is stored (if a full or partial path is used to load the initial
656DLL) and paths added by :func:`~os.add_dll_directory`.
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300657(Contributed by Steve Dower in :issue:`36085`.)
Steve Dower2438cdf2019-03-29 16:37:16 -0700658
659
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -0400660datetime
661--------
662
663Added new alternate constructors :meth:`datetime.date.fromisocalendar` and
664:meth:`datetime.datetime.fromisocalendar`, which construct :class:`date` and
665:class:`datetime` objects respectively from ISO year, week number, and weekday;
666these are the inverse of each class's ``isocalendar`` method.
667(Contributed by Paul Ganssle in :issue:`36004`.)
668
669
Raymond Hettingerb8218682019-05-26 11:27:35 -0700670functools
671---------
672
673:func:`functools.lru_cache` can now be used as a straight decorator rather
674than as a function returning a decorator. So both of these are now supported::
675
676 @lru_cache
677 def f(x):
678 ...
679
680 @lru_cache(maxsize=256)
681 def f(x):
682 ...
683
684(Contributed by Raymond Hettinger in :issue:`36772`.)
685
Stéphane Wirtel93b81e12019-10-18 09:14:18 +0200686Added a new :func:`functools.cached_property` decorator, for computed properties
687cached for the life of the instance. ::
688
689 import functools
690 import statistics
691
692 class Dataset:
693 def __init__(self, sequence_of_numbers):
694 self.data = sequence_of_numbers
695
696 @functools.cached_property
697 def variance(self):
698 return statistics.variance(self.data)
699
700(Contributed by Carl Meyer in :issue:`21145`)
701
Raymond Hettingerb8218682019-05-26 11:27:35 -0700702
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -0400703gc
704--
Paul Ganssle88c09372019-04-29 09:22:03 -0400705
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -0400706:func:`~gc.get_objects` can now receive an optional *generation* parameter
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300707indicating a generation to get objects from.
708(Contributed by Pablo Galindo in :issue:`36016`.)
Paul Ganssle88c09372019-04-29 09:22:03 -0400709
710
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500711gettext
712-------
713
714Added :func:`~gettext.pgettext` and its variants.
715(Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in :issue:`2504`.)
716
Terry Jan Reedya72ca902019-07-31 01:03:53 -0400717
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -0400718gzip
719----
720
721Added the *mtime* parameter to :func:`gzip.compress` for reproducible output.
722(Contributed by Guo Ci Teo in :issue:`34898`.)
723
724A :exc:`~gzip.BadGzipFile` exception is now raised instead of :exc:`OSError`
725for certain types of invalid or corrupt gzip files.
726(Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in
727:issue:`6584`.)
728
729
Terry Jan Reedya72ca902019-07-31 01:03:53 -0400730idlelib and IDLE
731----------------
732
733Output over N lines (50 by default) is squeezed down to a button.
734N can be changed in the PyShell section of the General page of the
735Settings dialog. Fewer, but possibly extra long, lines can be squeezed by
736right clicking on the output. Squeezed output can be expanded in place
737by double-clicking the button or into the clipboard or a separate window
738by right-clicking the button. (Contributed by Tal Einat in :issue:`1529353`.)
739
740Add "Run Customized" to the Run menu to run a module with customized
741settings. Any command line arguments entered are added to sys.argv.
742They also re-appear in the box for the next customized run. One can also
743suppress the normal Shell main module restart. (Contributed by Cheryl
744Sabella, Terry Jan Reedy, and others in :issue:`5680` and :issue:`37627`.)
745
746Add optional line numbers for IDLE editor windows. Windows
747open without line numbers unless set otherwise in the General
748tab of the configuration dialog. Line numbers for an existing
749window are shown and hidden in the Options menu.
750(Contributed by Tal Einat and Saimadhav Heblikar in :issue:`17535`.)
751
752The changes above have been backported to 3.7 maintenance releases.
753
754
Raymond Hettingerd1e768a2019-03-25 13:01:13 -0700755inspect
756-------
757
758The :func:`inspect.getdoc` function can now find docstrings for ``__slots__``
759if that attribute is a :class:`dict` where the values are docstrings.
760This provides documentation options similar to what we already have
761for :func:`property`, :func:`classmethod`, and :func:`staticmethod`::
762
763 class AudioClip:
764 __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
765 'duration': 'in seconds, rounded up to an integer'}
766 def __init__(self, bit_rate, duration):
767 self.bit_rate = round(bit_rate / 1000.0, 1)
768 self.duration = ceil(duration)
Pablo Galindo175421b2019-02-23 03:02:06 +0000769
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300770(Contributed by Raymond Hettinger in :issue:`36326`.)
771
Terry Jan Reedya72ca902019-07-31 01:03:53 -0400772
Victor Stinnerbc2aa812019-05-23 03:45:09 +0200773io
774--
775
776In development mode (:option:`-X` ``env``) and in debug build, the
777:class:`io.IOBase` finalizer now logs the exception if the ``close()`` method
778fails. The exception is ignored silently by default in release build.
779(Contributed by Victor Stinner in :issue:`18748`.)
780
781
HongWeipengf1944792018-11-07 18:09:32 +0800782json.tool
783---------
784
785Add option ``--json-lines`` to parse every input line as separate JSON object.
786(Contributed by Weipeng Hong in :issue:`31553`.)
787
Pablo Galindobc098512019-02-07 07:04:02 +0000788
789math
790----
791
Raymond Hettinger3ff59622019-02-16 11:00:42 -0800792Added new function :func:`math.dist` for computing Euclidean distance
793between two points. (Contributed by Raymond Hettinger in :issue:`33089`.)
794
795Expanded the :func:`math.hypot` function to handle multiple dimensions.
796Formerly, it only supported the 2-D case.
797(Contributed by Raymond Hettinger in :issue:`33089`.)
798
Pablo Galindobc098512019-02-07 07:04:02 +0000799Added new function, :func:`math.prod`, as analogous function to :func:`sum`
800that returns the product of a 'start' value (default: 1) times an iterable of
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700801numbers::
802
803 >>> prior = 0.8
804 >>> likelihoods = [0.625, 0.84, 0.30]
Ashwin Vishnu1a8de822019-09-09 14:42:27 +0200805 >>> math.prod(likelihoods, start=prior)
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -0700806 0.126
807
808(Contributed by Pablo Galindo in :issue:`35606`)
Pablo Galindobc098512019-02-07 07:04:02 +0000809
Mark Dickinson73934b92019-05-18 12:29:50 +0100810Added new function :func:`math.isqrt` for computing integer square roots.
811(Contributed by Mark Dickinson in :issue:`36887`.)
812
Mark Dickinsona0adffb2019-06-01 12:21:53 +0100813The function :func:`math.factorial` no longer accepts arguments that are not
814int-like. (Contributed by Pablo Galindo in :issue:`33083`.)
815
Zackery Spytz02db6962019-05-27 10:48:17 -0600816
817mmap
818----
819
820The :class:`mmap.mmap` class now has an :meth:`~mmap.mmap.madvise` method to
821access the ``madvise()`` system call.
822(Contributed by Zackery Spytz in :issue:`32941`.)
823
824
Victor Stinner17a55882019-05-28 16:02:50 +0200825multiprocessing
826---------------
827
828Added new :mod:`multiprocessing.shared_memory` module.
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300829(Contributed by Davin Potts in :issue:`35813`.)
Victor Stinner17a55882019-05-28 16:02:50 +0200830
831On macOS, the *spawn* start method is now used by default.
832(Contributed by Victor Stinner in :issue:`33725`.)
833
834
Steve Dower2438cdf2019-03-29 16:37:16 -0700835os
836--
837
838Added new function :func:`~os.add_dll_directory` on Windows for providing
839additional search paths for native dependencies when importing extension
840modules or loading DLLs using :mod:`ctypes`.
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300841(Contributed by Steve Dower in :issue:`36085`.)
Steve Dower2438cdf2019-03-29 16:37:16 -0700842
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600843A new :func:`os.memfd_create` function was added to wrap the
844``memfd_create()`` syscall.
845(Contributed by Zackery Spytz and Christian Heimes in :issue:`26836`.)
846
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700847On Windows, much of the manual logic for handling reparse points (including
848symlinks and directory junctions) has been delegated to the operating system.
849Specifically, :func:`os.stat` will now traverse anything supported by the
850operating system, while :func:`os.lstat` will only open reparse points that
851identify as "name surrogates" while others are opened as for :func:`os.stat`.
852In all cases, :attr:`stat_result.st_mode` will only have ``S_IFLNK`` set for
853symbolic links and not other kinds of reparse points. To identify other kinds
854of reparse point, check the new :attr:`stat_result.st_reparse_tag` attribute.
855
856On Windows, :func:`os.readlink` is now able to read directory junctions. Note
857that :func:`~os.path.islink` will return ``False`` for directory junctions,
858and so code that checks ``islink`` first will continue to treat junctions as
859directories, while code that handles errors from :func:`os.readlink` may now
860treat junctions as links.
861
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300862(Contributed by Steve Dower in :issue:`37834`.)
863
Pablo Galindobc098512019-02-07 07:04:02 +0000864
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300865os.path
866-------
867
868:mod:`os.path` functions that return a boolean result like
869:func:`~os.path.exists`, :func:`~os.path.lexists`, :func:`~os.path.isdir`,
870:func:`~os.path.isfile`, :func:`~os.path.islink`, and :func:`~os.path.ismount`
871now return ``False`` instead of raising :exc:`ValueError` or its subclasses
872:exc:`UnicodeEncodeError` and :exc:`UnicodeDecodeError` for paths that contain
873characters or bytes unrepresentable at the OS level.
874(Contributed by Serhiy Storchaka in :issue:`33721`.)
875
Steve Dower8ef864d2019-03-12 15:15:26 -0700876:func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
877environment variable and does not use :envvar:`HOME`, which is not normally set
878for regular user accounts.
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300879(Contributed by Anthony Sottile in :issue:`36264`.)
Steve Dower8ef864d2019-03-12 15:15:26 -0700880
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700881:func:`~os.path.isdir` on Windows no longer returns true for a link to a
882non-existent directory.
883
Steve Dower75e06492019-08-21 13:43:06 -0700884:func:`~os.path.realpath` on Windows now resolves reparse points, including
885symlinks and directory junctions.
886
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300887(Contributed by Steve Dower in :issue:`37834`.)
888
Serhiy Storchakab232df92018-10-30 13:22:42 +0200889
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300890pathlib
891-------
892
893:mod:`pathlib.Path` methods that return a boolean result like
894:meth:`~pathlib.Path.exists()`, :meth:`~pathlib.Path.is_dir()`,
895:meth:`~pathlib.Path.is_file()`, :meth:`~pathlib.Path.is_mount()`,
896:meth:`~pathlib.Path.is_symlink()`, :meth:`~pathlib.Path.is_block_device()`,
897:meth:`~pathlib.Path.is_char_device()`, :meth:`~pathlib.Path.is_fifo()`,
898:meth:`~pathlib.Path.is_socket()` now return ``False`` instead of raising
899:exc:`ValueError` or its subclass :exc:`UnicodeEncodeError` for paths that
900contain characters unrepresentable at the OS level.
901(Contributed by Serhiy Storchaka in :issue:`33721`.)
902
Joannah Nanjekye6b5b0132019-05-04 11:27:10 -0400903Added :meth:`pathlib.Path.link_to()` which creates a hard link pointing
904to a path.
905(Contributed by Joannah Nanjekye in :issue:`26978`)
906
jab9e00d9e2018-12-28 13:03:40 -0500907
Pierre Glaserec6c1bd2019-07-01 15:51:57 +0200908pickle
909------
910
911Reduction methods can now include a 6th item in the tuple they return. This
912item should specify a custom state-setting method that's called instead of the
913regular ``__setstate__`` method.
914(Contributed by Pierre Glaser and Olivier Grisel in :issue:`35900`)
915
916:mod:`pickle` extensions subclassing the C-optimized :class:`~pickle.Pickler`
917can now override the pickling logic of functions and classes by defining the
918special :meth:`~pickle.Pickler.reducer_override` method.
919(Contributed by Pierre Glaser and Olivier Grisel in :issue:`35900`)
920
921
Jon Janzenc981ad12019-05-15 22:14:38 +0200922plistlib
923--------
924
925Added new :class:`plistlib.UID` and enabled support for reading and writing
926NSKeyedArchiver-encoded binary plists.
927(Contributed by Jon Janzen in :issue:`26707`.)
928
929
Joannah Nanjekye2e33ecd2019-05-28 13:29:04 -0300930py_compile
931----------
932
933:func:`py_compile.compile` now supports silent mode.
934(Contributed by Joannah Nanjekye in :issue:`22640`.)
935
936
Bo Baylesca804952019-05-29 03:06:12 -0500937shlex
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300938-----
Bo Baylesca804952019-05-29 03:06:12 -0500939
940The new :func:`shlex.join` function acts as the inverse of :func:`shlex.split`.
941(Contributed by Bo Bayles in :issue:`32102`.)
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +0200942
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300943
jab9e00d9e2018-12-28 13:03:40 -0500944shutil
945------
946
947:func:`shutil.copytree` now accepts a new ``dirs_exist_ok`` keyword argument.
948(Contributed by Josh Bronson in :issue:`20849`.)
949
CAM Gerlach89a89442019-04-06 23:47:49 -0500950:func:`shutil.make_archive` now defaults to the modern pax (POSIX.1-2001)
951format for new archives to improve portability and standards conformance,
952inherited from the corresponding change to the :mod:`tarfile` module.
953(Contributed by C.A.M. Gerlach in :issue:`30661`.)
954
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700955:func:`shutil.rmtree` on Windows now removes directory junctions without
956recursively removing their contents first.
Serhiy Storchaka298439c2019-10-14 16:10:40 +0300957(Contributed by Steve Dower in :issue:`37834`.)
Steve Dowerdf2d4a62019-08-21 15:27:33 -0700958
jab9e00d9e2018-12-28 13:03:40 -0500959
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -0400960socket
961------
962
963Added :meth:`~socket.create_server()` and :meth:`~socket.has_dualstack_ipv6()`
964convenience functions to automate the necessary tasks usually involved when
965creating a server socket, including accepting both IPv4 and IPv6 connections
966on the same socket. (Contributed by Giampaolo Rodolà in :issue:`17561`.)
967
968The :func:`socket.if_nameindex()`, :func:`socket.if_nametoindex()`, and
969:func:`socket.if_indextoname()` functions have been implemented on Windows.
970(Contributed by Zackery Spytz in :issue:`37007`.)
971
972
Christian Heimes9fb051f2018-09-23 08:32:31 +0200973ssl
974---
975
Raymond Hettinger61a6db52019-10-13 21:31:12 -0700976Added :attr:`ssl.SSLContext.post_handshake_auth` to enable and
Christian Heimes9fb051f2018-09-23 08:32:31 +0200977:meth:`ssl.SSLSocket.verify_client_post_handshake` to initiate TLS 1.3
978post-handshake authentication.
979(Contributed by Christian Heimes in :issue:`34670`.)
980
Raymond Hettinger47d99872019-02-21 15:06:29 -0800981
982statistics
983----------
984
985Added :func:`statistics.fmean` as a faster, floating point variant of
986:func:`statistics.mean()`. (Contributed by Raymond Hettinger and
987Steven D'Aprano in :issue:`35904`.)
988
Raymond Hettinger6463ba32019-04-07 09:20:03 -0700989Added :func:`statistics.geometric_mean()`
990(Contributed by Raymond Hettinger in :issue:`27181`.)
991
Raymond Hettingerfc06a192019-03-12 00:43:27 -0700992Added :func:`statistics.multimode` that returns a list of the most
993common values. (Contributed by Raymond Hettinger in :issue:`35892`.)
994
Raymond Hettinger9013ccf2019-04-23 00:06:35 -0700995Added :func:`statistics.quantiles` that divides data or a distribution
996in to equiprobable intervals (e.g. quartiles, deciles, or percentiles).
997(Contributed by Raymond Hettinger in :issue:`36546`.)
998
Raymond Hettinger11c79532019-02-23 14:44:07 -0800999Added :class:`statistics.NormalDist`, a tool for creating
1000and manipulating normal distributions of a random variable.
1001(Contributed by Raymond Hettinger in :issue:`36018`.)
1002
1003::
1004
1005 >>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
Raymond Hettinger671d7822019-05-01 17:49:12 -07001006 >>> temperature_feb.mean
1007 6.0
1008 >>> temperature_feb.stdev
1009 6.356099432828281
Raymond Hettinger11c79532019-02-23 14:44:07 -08001010
1011 >>> temperature_feb.cdf(3) # Chance of being under 3 degrees
1012 0.3184678262814532
1013 >>> # Relative chance of being 7 degrees versus 10 degrees
1014 >>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
1015 1.2039930378537762
1016
Raymond Hettinger671d7822019-05-01 17:49:12 -07001017 >>> el_niño = NormalDist(4, 2.5)
1018 >>> temperature_feb += el_niño # Add in a climate effect
Raymond Hettinger11c79532019-02-23 14:44:07 -08001019 >>> temperature_feb
1020 NormalDist(mu=10.0, sigma=6.830080526611674)
1021
1022 >>> temperature_feb * (9/5) + 32 # Convert to Fahrenheit
1023 NormalDist(mu=50.0, sigma=12.294144947901014)
1024 >>> temperature_feb.samples(3) # Generate random samples
1025 [7.672102882379219, 12.000027119750287, 4.647488369766392]
1026
Raymond Hettinger47d99872019-02-21 15:06:29 -08001027
Victor Stinneref9d9b62019-05-22 11:28:22 +02001028sys
1029---
1030
1031Add new :func:`sys.unraisablehook` function which can be overridden to control
1032how "unraisable exceptions" are handled. It is called when an exception has
1033occurred but there is no way for Python to handle it. For example, when a
1034destructor raises an exception or during garbage collection
1035(:func:`gc.collect`).
Victor Stinner01ae8972019-06-03 16:28:01 +02001036(Contributed by Victor Stinner in :issue:`36829`.)
Victor Stinneref9d9b62019-05-22 11:28:22 +02001037
1038
CAM Gerlache680c3d2019-03-21 09:44:51 -05001039tarfile
1040-------
1041
1042The :mod:`tarfile` module now defaults to the modern pax (POSIX.1-2001)
1043format for new archives, instead of the previous GNU-specific one.
1044This improves cross-platform portability with a consistent encoding (UTF-8)
1045in a standardized and extensible format, and offers several other benefits.
1046(Contributed by C.A.M. Gerlach in :issue:`36268`.)
1047
1048
Victor Stinnercd590a72019-05-28 00:39:52 +02001049threading
1050---------
1051
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001052Add a new :func:`threading.excepthook` function which handles uncaught
1053:meth:`threading.Thread.run` exception. It can be overridden to control how
1054uncaught :meth:`threading.Thread.run` exceptions are handled.
1055(Contributed by Victor Stinner in :issue:`1230540`.)
Jake Tesler84846b02019-07-30 14:41:46 -07001056
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001057Add a new :func:`threading.get_native_id` function and
1058a :data:`~threading.Thread.native_id`
1059attribute to the :class:`threading.Thread` class. These return the native
1060integral Thread ID of the current thread assigned by the kernel.
1061This feature is only available on certain platforms, see
1062:func:`get_native_id <threading.get_native_id>` for more information.
1063(Contributed by Jake Tesler in :issue:`36084`.)
Victor Stinnercd590a72019-05-28 00:39:52 +02001064
1065
Tal Einatdfba1f62018-10-24 10:20:05 +03001066tokenize
1067--------
1068
1069The :mod:`tokenize` module now implicitly emits a ``NEWLINE`` token when
1070provided with input that does not have a trailing new line. This behavior
1071now matches what the C tokenizer does internally.
1072(Contributed by Ammar Askar in :issue:`33899`.)
1073
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001074
Juliette Monselaf5658a2018-10-08 18:29:24 +02001075tkinter
1076-------
1077
1078Added methods :meth:`~tkinter.Spinbox.selection_from`,
1079:meth:`~tkinter.Spinbox.selection_present`,
1080:meth:`~tkinter.Spinbox.selection_range` and
1081:meth:`~tkinter.Spinbox.selection_to`
1082in the :class:`tkinter.Spinbox` class.
1083(Contributed by Juliette Monsel in :issue:`34829`.)
1084
Juliette Monselbf034712018-10-12 18:44:10 +02001085Added method :meth:`~tkinter.Canvas.moveto`
1086in the :class:`tkinter.Canvas` class.
1087(Contributed by Juliette Monsel in :issue:`23831`.)
1088
Zackery Spytz50866e92019-04-05 04:17:13 -06001089The :class:`tkinter.PhotoImage` class now has
1090:meth:`~tkinter.PhotoImage.transparency_get` and
1091:meth:`~tkinter.PhotoImage.transparency_set` methods. (Contributed by
1092Zackery Spytz in :issue:`25451`.)
1093
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001094
Joannah Nanjekye572168a2019-01-10 19:56:38 +03001095time
1096----
1097
1098Added new clock :data:`~time.CLOCK_UPTIME_RAW` for macOS 10.12.
1099(Contributed by Joannah Nanjekye in :issue:`35702`.)
1100
Guido van Rossum9b33ce42019-06-11 13:42:35 -07001101
1102typing
1103------
1104
1105The :mod:`typing` module incorporates several new features:
1106
Guido van Rossum9b33ce42019-06-11 13:42:35 -07001107* A dictionary type with per-key types. See :pep:`589` and
1108 :class:`typing.TypedDict`.
Raymond Hettingera3291532019-10-13 23:32:03 -07001109 TypedDict uses only string keys. By default, every key is required
1110 to be present. Specify "total=False" to allow keys to be optional::
1111
1112 class Location(TypedDict, total=False):
1113 lat_long: tuple
1114 grid_square: str
1115 xy_coordinate: tuple
Guido van Rossum9b33ce42019-06-11 13:42:35 -07001116
1117* Literal types. See :pep:`586` and :class:`typing.Literal`.
Raymond Hettingera3291532019-10-13 23:32:03 -07001118 Literal types indicate that a parameter or return value
1119 is constrained to one or more specific literal values::
1120
1121 def get_status(port: int) -> Literal['connected', 'disconnected']:
1122 ...
Guido van Rossum9b33ce42019-06-11 13:42:35 -07001123
1124* "Final" variables, functions, methods and classes. See :pep:`591`,
1125 :class:`typing.Final` and :func:`typing.final`.
Raymond Hettingera3291532019-10-13 23:32:03 -07001126 The final qualifier instructs a static type checker to restrict
1127 subclassing, overriding, or reassignment::
1128
1129 pi: Final[float] = 3.1415926536
1130
1131* Protocol definitions. See :pep:`544`, :class:`typing.Protocol` and
1132 :func:`typing.runtime_checkable`. Simple ABCs like
1133 :class:`typing.SupportsInt` are now ``Protocol`` subclasses.
Guido van Rossum9b33ce42019-06-11 13:42:35 -07001134
1135* New protocol class :class:`typing.SupportsIndex`.
1136
1137* New functions :func:`typing.get_origin` and :func:`typing.get_args`.
1138
1139
Max Bélanger2810dd72018-11-04 15:58:24 -08001140unicodedata
1141-----------
1142
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001143The :mod:`unicodedata` module has been upgraded to use the `Unicode 12.1.0
1144<http://blog.unicode.org/2019/05/unicode-12-1-en.html>`_ release.
Raymond Hettinger482b6b52019-05-01 17:48:13 -07001145
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001146New function :func:`~unicodedata.is_normalized` can be used to verify a string
1147is in a specific normal form, often much faster than by actually normalizing
1148the string. (Contributed by Max Belanger, David Euresti, and Greg Price in
1149:issue:`32285` and :issue:`37966`).
Max Bélanger2810dd72018-11-04 15:58:24 -08001150
Raymond Hettinger482b6b52019-05-01 17:48:13 -07001151
Lisa Roach0f221d02018-11-08 18:34:33 -08001152unittest
1153--------
1154
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001155Added :class:`AsyncMock` to support an asynchronous version of :class:`Mock`.
1156Appropriate new assert functions for testing have been added as well.
1157(Contributed by Lisa Roach in :issue:`26467`).
Lisa Roach77b3b772019-05-20 09:19:53 -07001158
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001159Added :func:`~unittest.addModuleCleanup()` and
1160:meth:`~unittest.TestCase.addClassCleanup()` to unittest to support
1161cleanups for :func:`~unittest.setUpModule()` and
1162:meth:`~unittest.TestCase.setUpClass()`.
1163(Contributed by Lisa Roach in :issue:`24412`.)
Lisa Roach0f221d02018-11-08 18:34:33 -08001164
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001165Several mock assert functions now also print a list of actual calls upon
1166failure. (Contributed by Petter Strandmark in :issue:`35047`.)
Petter Strandmark001d63c2019-06-04 21:34:49 +02001167
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001168:mod:`unittest` module gained support for coroutines to be used as test cases
1169with :class:`unittest.IsolatedAsyncioTestCase`.
1170(Contributed by Andrew Svetlov in :issue:`32972`.)
Xtreak6a9fd662019-09-11 12:02:14 +01001171
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001172Example::
Xtreak6a9fd662019-09-11 12:02:14 +01001173
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001174 import unittest
Xtreak6a9fd662019-09-11 12:02:14 +01001175
1176
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001177 class TestRequest(unittest.IsolatedAsyncioTestCase):
Xtreak6a9fd662019-09-11 12:02:14 +01001178
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001179 async def asyncSetUp(self):
1180 self.connection = await AsyncConnection()
Xtreak6a9fd662019-09-11 12:02:14 +01001181
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001182 async def test_get(self):
1183 response = await self.connection.get("https://example.com")
1184 self.assertEqual(response.status_code, 200)
Xtreak6a9fd662019-09-11 12:02:14 +01001185
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001186 async def asyncTearDown(self):
1187 await self.connection.close()
Xtreak6a9fd662019-09-11 12:02:14 +01001188
1189
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001190 if __name__ == "__main__":
1191 unittest.main()
Xtreak6a9fd662019-09-11 12:02:14 +01001192
1193
Brett Cannond64ee1a2018-09-21 15:27:26 -07001194venv
1195----
1196
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001197:mod:`venv` now includes an ``Activate.ps1`` script on all platforms for
1198activating virtual environments under PowerShell Core 6.1.
1199(Contributed by Brett Cannon in :issue:`32718`.)
1200
Brett Cannond64ee1a2018-09-21 15:27:26 -07001201
Mark Dickinson7abb6c02019-04-26 15:56:15 +09001202weakref
1203-------
1204
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001205The proxy objects returned by :func:`weakref.proxy` now support the matrix
1206multiplication operators ``@`` and ``@=`` in addition to the other
1207numeric operators. (Contributed by Mark Dickinson in :issue:`36669`.)
1208
Mark Dickinson7abb6c02019-04-26 15:56:15 +09001209
Christian Heimes17b1d5d2018-09-23 09:50:25 +02001210xml
1211---
1212
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001213As mitigation against DTD and external entity retrieval, the
1214:mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
1215external entities by default.
1216(Contributed by Christian Heimes in :issue:`17239`.)
Christian Heimes17b1d5d2018-09-23 09:50:25 +02001217
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001218The ``.find*()`` methods in the :mod:`xml.etree.ElementTree` module
1219support wildcard searches like ``{*}tag`` which ignores the namespace
1220and ``{namespace}*`` which returns all tags in the given namespace.
1221(Contributed by Stefan Behnel in :issue:`28238`.)
Stefan Behnel47541682019-05-03 20:58:16 +02001222
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001223The :mod:`xml.etree.ElementTree` module provides a new function
1224:func:`–xml.etree.ElementTree.canonicalize()` that implements C14N 2.0.
1225(Contributed by Stefan Behnel in :issue:`13611`.)
Stefan Behnele1d5dd62019-05-01 22:34:13 +02001226
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001227The target object of :class:`xml.etree.ElementTree.XMLParser` can
1228receive namespace declaration events through the new callback methods
1229``start_ns()`` and ``end_ns()``. Additionally, the
1230:class:`xml.etree.ElementTree.TreeBuilder` target can be configured
1231to process events about comments and processing instructions to include
1232them in the generated tree.
1233(Contributed by Stefan Behnel in :issue:`36676` and :issue:`36673`.)
1234
Christian Heimes17b1d5d2018-09-23 09:50:25 +02001235
Ned Deily07a18922018-01-31 18:12:38 -05001236Optimizations
1237=============
1238
Victor Stinner9daecf32019-01-16 00:02:35 +01001239* The :mod:`subprocess` module can now use the :func:`os.posix_spawn` function
1240 in some cases for better performance. Currently, it is only used on macOS
1241 and Linux (using glibc 2.24 or newer) if all these conditions are met:
1242
1243 * *close_fds* is false;
Victor Stinnerf6243ac2019-01-23 19:00:39 +01001244 * *preexec_fn*, *pass_fds*, *cwd* and *start_new_session* parameters
1245 are not set;
Victor Stinner8c349562019-01-16 23:38:06 +01001246 * the *executable* path contains a directory.
Victor Stinner9daecf32019-01-16 00:02:35 +01001247
Victor Stinner01ae8972019-06-03 16:28:01 +02001248 (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
1249
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02001250* :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
1251 :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
Giampaolo Rodola413d9552019-05-30 14:05:41 +08001252 "fast-copy" syscalls on Linux and macOS in order to copy the file
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07001253 more efficiently.
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02001254 "fast-copy" means that the copying operation occurs within the kernel,
1255 avoiding the use of userspace buffers in Python as in
1256 "``outfd.write(infd.read())``".
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07001257 On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB
1258 instead of 16 KiB) and a :func:`memoryview`-based variant of
1259 :func:`shutil.copyfileobj` is used.
1260 The speedup for copying a 512 MiB file within the same partition is about
1261 +26% on Linux, +50% on macOS and +40% on Windows. Also, much less CPU cycles
1262 are consumed.
1263 See :ref:`shutil-platform-dependent-efficient-copy-operations` section.
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001264 (Contributed by Giampaolo Rodolà in :issue:`33671`.)
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +02001265
Giampaolo Rodola19c46a42018-11-12 06:18:15 -08001266* :func:`shutil.copytree` uses :func:`os.scandir` function and all copy
1267 functions depending from it use cached :func:`os.stat` values. The speedup
1268 for copying a directory with 8000 files is around +9% on Linux, +20% on
1269 Windows and +30% on a Windows SMB share. Also the number of :func:`os.stat`
1270 syscalls is reduced by 38% making :func:`shutil.copytree` especially faster
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001271 on network filesystems. (Contributed by Giampaolo Rodolà in :issue:`33695`.)
Giampaolo Rodola19c46a42018-11-12 06:18:15 -08001272
Łukasz Langac51d8c92018-04-03 23:06:53 -07001273* The default protocol in the :mod:`pickle` module is now Protocol 4,
1274 first introduced in Python 3.4. It offers better performance and smaller
1275 size compared to Protocol 3 available since Python 3.0.
Ned Deily07a18922018-01-31 18:12:38 -05001276
INADA Naokid5c875b2018-07-11 17:42:49 +09001277* Removed one ``Py_ssize_t`` member from ``PyGC_Head``. All GC tracked
1278 objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.
1279 (Contributed by Inada Naoki in :issue:`33597`)
1280
Tal Einat54752532018-09-10 16:11:04 +03001281* :class:`uuid.UUID` now uses ``__slots__`` to reduce its memory footprint.
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001282 (Contributed by Wouter Bolsterlee and Tal Einat in :issue:`30977`)
Tal Einat54752532018-09-10 16:11:04 +03001283
Raymond Hettinger63fa1cf2019-02-16 12:02:22 -08001284* Improved performance of :func:`operator.itemgetter` by 33%. Optimized
1285 argument handling and added a fast path for the common case of a single
1286 non-negative integer index into a tuple (which is the typical use case in
1287 the standard library). (Contributed by Raymond Hettinger in
1288 :issue:`35664`.)
1289
1290* Sped-up field lookups in :func:`collections.namedtuple`. They are now more
1291 than two times faster, making them the fastest form of instance variable
1292 lookup in Python. (Contributed by Raymond Hettinger, Pablo Galindo, and
Joe Jevnikf36f8922019-02-21 16:00:40 -05001293 Joe Jevnik, Serhiy Storchaka in :issue:`32492`.)
Raymond Hettinger63fa1cf2019-02-16 12:02:22 -08001294
Pablo Galindoc61e2292018-10-28 22:03:18 +00001295* The :class:`list` constructor does not overallocate the internal item buffer
1296 if the input iterable has a known length (the input implements ``__len__``).
Raymond Hettingere1823182019-02-16 12:47:48 -08001297 This makes the created list 12% smaller on average. (Contributed by
1298 Raymond Hettinger and Pablo Galindo in :issue:`33234`.)
Pablo Galindoc61e2292018-10-28 22:03:18 +00001299
Stefan Behneld8b9e1f2019-02-20 18:29:24 +01001300* Doubled the speed of class variable writes. When a non-dunder attribute
1301 was updated, there was an unnecessary call to update slots.
1302 (Contributed by Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger,
1303 Neil Schemenauer, and Serhiy Storchaka in :issue:`36012`.)
1304
Serhiy Storchaka31913912019-03-14 10:32:22 +02001305* Reduced an overhead of converting arguments passed to many builtin functions
1306 and methods. This sped up calling some simple builtin functions and
1307 methods up to 20--50%. (Contributed by Serhiy Storchaka in :issue:`23867`,
1308 :issue:`35582` and :issue:`36127`.)
1309
Inada Naoki91234a12019-06-03 21:30:58 +09001310* ``LOAD_GLOBAL`` instruction now uses new "per opcode cache" mechanism.
1311 It is about 40% faster now. (Contributed by Yury Selivanov and Inada Naoki in
1312 :issue:`26219`.)
1313
Serhiy Storchakaceeef102018-06-15 11:09:43 +03001314
Ned Deily07a18922018-01-31 18:12:38 -05001315Build and C API Changes
1316=======================
1317
Victor Stinner7efc5262019-06-15 03:24:41 +02001318* Default :data:`sys.abiflags` became an empty string: the ``m`` flag for
1319 pymalloc became useless (builds with and without pymalloc are ABI compatible)
1320 and so has been removed. (Contributed by Victor Stinner in :issue:`36707`.)
1321
1322 Example of changes:
1323
1324 * Only ``python3.8`` program is installed, ``python3.8m`` program is gone.
1325 * Only ``python3.8-config`` script is installed, ``python3.8m-config`` script
1326 is gone.
1327 * The ``m`` flag has been removed from the suffix of dynamic library
1328 filenames: extension modules in the standard library as well as those
1329 produced and installed by third-party packages, like those downloaded from
1330 PyPI. On Linux, for example, the Python 3.7 suffix
1331 ``.cpython-37m-x86_64-linux-gnu.so`` became
1332 ``.cpython-38-x86_64-linux-gnu.so`` in Python 3.8.
1333
Victor Stinnerbd5798f2019-06-14 19:43:43 +02001334* The header files have been reorganized to better separate the different kinds
1335 of APIs:
1336
1337 * ``Include/*.h`` should be the portable public stable C API.
1338 * ``Include/cpython/*.h`` should be the unstable C API specific to CPython;
Victor Stinneraf41c562019-06-20 01:44:58 +02001339 public API, with some private API prefixed by ``_Py`` or ``_PY``.
Victor Stinnerbd5798f2019-06-14 19:43:43 +02001340 * ``Include/internal/*.h`` is the private internal C API very specific to
1341 CPython. This API comes with no backward compatibility warranty and should
1342 not be used outside CPython. It is only exposed for very specific needs
1343 like debuggers and profiles which has to access to CPython internals
1344 without calling functions. This API is now installed by ``make install``.
1345
1346 (Contributed by Victor Stinner in :issue:`35134` and :issue:`35081`,
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001347 work initiated by Eric Snow in Python 3.7.)
Victor Stinnerbd5798f2019-06-14 19:43:43 +02001348
1349* Some macros have been converted to static inline functions: parameter types
1350 and return type are well defined, they don't have issues specific to macros,
1351 variables have a local scopes. Examples:
1352
1353 * :c:func:`Py_INCREF`, :c:func:`Py_DECREF`
1354 * :c:func:`Py_XINCREF`, :c:func:`Py_XDECREF`
1355 * :c:func:`PyObject_INIT`, :c:func:`PyObject_INIT_VAR`
1356 * Private functions: :c:func:`_PyObject_GC_TRACK`,
1357 :c:func:`_PyObject_GC_UNTRACK`, :c:func:`_Py_Dealloc`
1358
1359 (Contributed by Victor Stinner in :issue:`35059`.)
1360
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001361* The :c:func:`PyByteArray_Init` and :c:func:`PyByteArray_Fini` functions have
1362 been removed. They did nothing since Python 2.7.4 and Python 3.2.0, were
1363 excluded from the limited API (stable ABI), and were not documented.
Victor Stinnerc68e3fb2019-06-20 22:41:25 +02001364 (Contributed by Victor Stinner in :issue:`35713`.)
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +01001365
Serhiy Storchakaceeef102018-06-15 11:09:43 +03001366* The result of :c:func:`PyExceptionClass_Name` is now of type
1367 ``const char *`` rather of ``char *``.
1368 (Contributed by Serhiy Storchaka in :issue:`33818`.)
Ned Deily07a18922018-01-31 18:12:38 -05001369
Antoine Pitrou961d54c2018-07-16 19:03:03 +02001370* The duality of ``Modules/Setup.dist`` and ``Modules/Setup`` has been
1371 removed. Previously, when updating the CPython source tree, one had
1372 to manually copy ``Modules/Setup.dist`` (inside the source tree) to
1373 ``Modules/Setup`` (inside the build tree) in order to reflect any changes
1374 upstream. This was of a small benefit to packagers at the expense of
1375 a frequent annoyance to developers following CPython development, as
1376 forgetting to copy the file could produce build failures.
1377
1378 Now the build system always reads from ``Modules/Setup`` inside the source
1379 tree. People who want to customize that file are encouraged to maintain
1380 their changes in a git fork of CPython or as patch files, as they would do
1381 for any other change to the source tree.
1382
1383 (Contributed by Antoine Pitrou in :issue:`32430`.)
1384
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001385* Functions that convert Python number to C integer like
1386 :c:func:`PyLong_AsLong` and argument parsing functions like
1387 :c:func:`PyArg_ParseTuple` with integer converting format units like ``'i'``
1388 will now use the :meth:`~object.__index__` special method instead of
1389 :meth:`~object.__int__`, if available. The deprecation warning will be
1390 emitted for objects with the ``__int__()`` method but without the
1391 ``__index__()`` method (like :class:`~decimal.Decimal` and
1392 :class:`~fractions.Fraction`). :c:func:`PyNumber_Check` will now return
1393 ``1`` for objects implementing ``__index__()``.
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001394 :c:func:`PyNumber_Long`, :c:func:`PyNumber_Float` and
1395 :c:func:`PyFloat_AsDouble` also now use the ``__index__()`` method if
1396 available.
1397 (Contributed by Serhiy Storchaka in :issue:`36048` and :issue:`20092`.)
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001398
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001399* Heap-allocated type objects will now increase their reference count
1400 in :c:func:`PyObject_Init` (and its parallel macro ``PyObject_INIT``)
1401 instead of in :c:func:`PyType_GenericAlloc`. Types that modify instance
1402 allocation or deallocation may need to be adjusted.
1403 (Contributed by Eddie Elizondo in :issue:`35810`.)
1404
Pablo Galindo4a2edc32019-07-01 11:35:05 +01001405* The new function :c:func:`PyCode_NewWithPosOnlyArgs` allows to create
1406 code objects like :c:func:`PyCode_New`, but with an extra *posonlyargcount*
1407 parameter for indicating the number of positional-only arguments.
1408 (Contributed by Pablo Galindo in :issue:`37221`.)
1409
Victor Stinner1ce152a2019-09-24 17:44:15 +02001410* :c:func:`Py_SetPath` now sets :data:`sys.executable` to the program full
1411 path (:c:func:`Py_GetProgramFullPath`) rather than to the program name
1412 (:c:func:`Py_GetProgramName`).
1413 (Contributed by Victor Stinner in :issue:`38234`.)
1414
Ned Deily07a18922018-01-31 18:12:38 -05001415
1416Deprecated
1417==========
1418
Victor Stinner1da44622019-07-05 10:44:12 +02001419* The distutils ``bdist_wininst`` command is now deprecated, use
1420 ``bdist_wheel`` (wheel packages) instead.
1421 (Contributed by Victor Stinner in :issue:`37481`.)
1422
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001423* Deprecated methods ``getchildren()`` and ``getiterator()`` in
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001424 the :mod:`~xml.etree.ElementTree` module now emit a
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001425 :exc:`DeprecationWarning` instead of :exc:`PendingDeprecationWarning`.
1426 They will be removed in Python 3.9.
1427 (Contributed by Serhiy Storchaka in :issue:`29209`.)
Ned Deily07a18922018-01-31 18:12:38 -05001428
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001429* Passing an object that is not an instance of
1430 :class:`concurrent.futures.ThreadPoolExecutor` to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001431 :meth:`asyncio.loop.set_default_executor()` is
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001432 deprecated and will be prohibited in Python 3.9.
1433 (Contributed by Elvis Pranskevichus in :issue:`34075`.)
1434
Berker Peksagef8861c2018-08-21 17:58:49 +03001435* The :meth:`__getitem__` methods of :class:`xml.dom.pulldom.DOMEventStream`,
1436 :class:`wsgiref.util.FileWrapper` and :class:`fileinput.FileInput` have been
1437 deprecated.
1438
1439 Implementations of these methods have been ignoring their *index* parameter,
1440 and returning the next item instead.
Berker Peksagef8861c2018-08-21 17:58:49 +03001441 (Contributed by Berker Peksag in :issue:`9372`.)
1442
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07001443* The :class:`typing.NamedTuple` class has deprecated the ``_field_types``
1444 attribute in favor of the ``__annotations__`` attribute which has the same
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001445 information. (Contributed by Raymond Hettinger in :issue:`36320`.)
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07001446
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001447* :mod:`ast` classes ``Num``, ``Str``, ``Bytes``, ``NameConstant`` and
1448 ``Ellipsis`` are considered deprecated and will be removed in future Python
1449 versions. :class:`~ast.Constant` should be used instead.
1450 (Contributed by Serhiy Storchaka in :issue:`32892`.)
1451
Serhiy Storchakac3ea41e2019-08-26 10:13:19 +03001452* :class:`ast.NodeVisitor` methods ``visit_Num()``, ``visit_Str()``,
1453 ``visit_Bytes()``, ``visit_NameConstant()`` and ``visit_Ellipsis()`` are
1454 deprecated now and will not be called in future Python versions.
1455 Add the :meth:`~ast.NodeVisitor.visit_Constant` method to handle all
1456 constant nodes.
1457 (Contributed by Serhiy Storchaka in :issue:`36917`.)
1458
Serhiy Storchakafec35c92018-10-27 08:00:41 +03001459* The following functions and methods are deprecated in the :mod:`gettext`
1460 module: :func:`~gettext.lgettext`, :func:`~gettext.ldgettext`,
1461 :func:`~gettext.lngettext` and :func:`~gettext.ldngettext`.
1462 They return encoded bytes, and it's possible that you will get unexpected
1463 Unicode-related exceptions if there are encoding problems with the
1464 translated strings. It's much better to use alternatives which return
1465 Unicode strings in Python 3. These functions have been broken for a long time.
1466
1467 Function :func:`~gettext.bind_textdomain_codeset`, methods
1468 :meth:`~gettext.NullTranslations.output_charset` and
1469 :meth:`~gettext.NullTranslations.set_output_charset`, and the *codeset*
1470 parameter of functions :func:`~gettext.translation` and
1471 :func:`~gettext.install` are also deprecated, since they are only used for
1472 for the ``l*gettext()`` functions.
Serhiy Storchakafec35c92018-10-27 08:00:41 +03001473 (Contributed by Serhiy Storchaka in :issue:`33710`.)
1474
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001475* The :meth:`~threading.Thread.isAlive()` method of :class:`threading.Thread`
1476 has been deprecated.
Dong-hee Na89669ff2019-01-17 21:14:45 +09001477 (Contributed by Dong-hee Na in :issue:`35283`.)
Ned Deily07a18922018-01-31 18:12:38 -05001478
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001479* Many builtin and extension functions that take integer arguments will
1480 now emit a deprecation warning for :class:`~decimal.Decimal`\ s,
1481 :class:`~fractions.Fraction`\ s and any other objects that can be converted
1482 to integers only with a loss (e.g. that have the :meth:`~object.__int__`
1483 method but do not have the :meth:`~object.__index__` method). In future
1484 version they will be errors.
1485 (Contributed by Serhiy Storchaka in :issue:`36048`.)
1486
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001487* Deprecated passing the following arguments as keyword arguments:
1488
1489 - *func* in :func:`functools.partialmethod`, :func:`weakref.finalize`,
1490 :meth:`profile.Profile.runcall`, :meth:`cProfile.Profile.runcall`,
1491 :meth:`bdb.Bdb.runcall`, :meth:`trace.Trace.runfunc` and
1492 :func:`curses.wrapper`.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001493 - *function* in :meth:`unittest.TestCase.addCleanup`.
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001494 - *fn* in the :meth:`~concurrent.futures.Executor.submit` method of
1495 :class:`concurrent.futures.ThreadPoolExecutor` and
1496 :class:`concurrent.futures.ProcessPoolExecutor`.
1497 - *callback* in :meth:`contextlib.ExitStack.callback`,
1498 :meth:`contextlib.AsyncExitStack.callback` and
1499 :meth:`contextlib.AsyncExitStack.push_async_callback`.
1500 - *c* and *typeid* in the :meth:`~multiprocessing.managers.Server.create`
1501 method of :class:`multiprocessing.managers.Server` and
1502 :class:`multiprocessing.managers.SharedMemoryServer`.
1503 - *obj* in :func:`weakref.finalize`.
1504
1505 In future releases of Python they will be :ref:`positional-only
1506 <positional-only_parameter>`.
1507 (Contributed by Serhiy Storchaka in :issue:`36492`.)
1508
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001509
Victor Stinner73104fa2018-11-29 09:58:20 +01001510API and Feature Removals
1511========================
1512
1513The following features and APIs have been removed from Python 3.8:
1514
Victor Stinnerd7538dd2018-12-14 13:37:26 +01001515* The :mod:`macpath` module, deprecated in Python 3.7, has been removed.
1516 (Contributed by Victor Stinner in :issue:`35471`.)
1517
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001518* The function :func:`platform.popen` has been removed, after having been
1519 deprecated since Python 3.3: use :func:`os.popen` instead.
Victor Stinner01ae8972019-06-03 16:28:01 +02001520 (Contributed by Victor Stinner in :issue:`35345`.)
Ned Deily07a18922018-01-31 18:12:38 -05001521
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001522* The function :func:`time.clock` has been removed, after having been
1523 deprecated since Python 3.3: use :func:`time.perf_counter` or
1524 :func:`time.process_time` instead, depending
1525 on your requirements, to have well-defined behavior.
Victor Stinner01ae8972019-06-03 16:28:01 +02001526 (Contributed by Matthias Bussonnier in :issue:`36895`.)
Matthias Bussonnierb6a09ae2019-05-13 12:23:07 -07001527
Brett Cannona8c34242018-04-20 14:15:40 -07001528* The ``pyvenv`` script has been removed in favor of ``python3.8 -m venv``
1529 to help eliminate confusion as to what Python interpreter the ``pyvenv``
1530 script is tied to. (Contributed by Brett Cannon in :issue:`25427`.)
Ned Deily07a18922018-01-31 18:12:38 -05001531
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001532* ``parse_qs``, ``parse_qsl``, and ``escape`` are removed from the :mod:`cgi`
1533 module. They are deprecated in Python 3.2 or older. They should be imported
Simon Willison1abf5432019-09-11 09:25:26 -05001534 from the ``urllib.parse`` and ``html`` modules instead.
INADA Naoki698865d2018-06-19 17:28:50 +09001535
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001536* ``filemode`` function is removed from the :mod:`tarfile` module.
INADA Naoki461a1c42018-06-28 17:10:36 +09001537 It is not documented and deprecated since Python 3.3.
INADA Naoki698865d2018-06-19 17:28:50 +09001538
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001539* The :class:`~xml.etree.ElementTree.XMLParser` constructor no longer accepts
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001540 the *html* argument. It never had an effect and was deprecated in Python 3.4.
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001541 All other parameters are now :ref:`keyword-only <keyword-only_parameter>`.
1542 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1543
1544* Removed the ``doctype()`` method of :class:`~xml.etree.ElementTree.XMLParser`.
1545 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1546
Inada Naoki6a16b182019-03-18 15:44:11 +09001547* "unicode_internal" codec is removed.
1548 (Contributed by Inada Naoki in :issue:`36297`.)
1549
Aviv Palivodae6576242019-05-09 21:05:45 +03001550* The ``Cache`` and ``Statement`` objects of the :mod:`sqlite3` module are not
1551 exposed to the user.
1552 (Contributed by Aviv Palivoda in :issue:`30262`.)
1553
Matthias Bussonnier1a3faf92019-05-20 13:44:11 -07001554* The ``bufsize`` keyword argument of :func:`fileinput.input` and
1555 :func:`fileinput.FileInput` which was ignored and deprecated since Python 3.6
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001556 has been removed. :issue:`36952` (Contributed by Matthias Bussonnier.)
Matthias Bussonnier1a3faf92019-05-20 13:44:11 -07001557
Matthias Bussonnier382034b2019-05-28 10:30:35 -07001558* The functions :func:`sys.set_coroutine_wrapper` and
1559 :func:`sys.get_coroutine_wrapper` deprecated in Python 3.7 have been removed;
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001560 :issue:`36933` (Contributed by Matthias Bussonnier.)
Matthias Bussonnier3880f262019-05-28 00:10:59 -07001561
Ned Deily07a18922018-01-31 18:12:38 -05001562
1563Porting to Python 3.8
1564=====================
1565
1566This section lists previously described changes and other bugfixes
1567that may require changes to your code.
1568
1569
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001570Changes in Python behavior
1571--------------------------
1572
1573* Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
1574 in comprehensions and generator expressions (aside from the iterable expression
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001575 in the leftmost :keyword:`!for` clause).
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001576 (Contributed by Serhiy Storchaka in :issue:`10544`.)
1577
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001578* The compiler now produces a :exc:`SyntaxWarning` when identity checks
1579 (``is`` and ``is not``) are used with certain types of literals
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001580 (e.g. strings, numbers). These can often work by accident in CPython,
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001581 but are not guaranteed by the language spec. The warning advises users
1582 to use equality tests (``==`` and ``!=``) instead.
1583 (Contributed by Serhiy Storchaka in :issue:`34850`.)
1584
Serhiy Storchaka7a0630c2019-04-08 14:34:04 +03001585* The CPython interpreter can swallow exceptions in some circumstances.
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001586 In Python 3.8 this happens in fewer cases. In particular, exceptions
Serhiy Storchaka7a0630c2019-04-08 14:34:04 +03001587 raised when getting the attribute from the type dictionary are no longer
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001588 ignored. (Contributed by Serhiy Storchaka in :issue:`35459`.)
Serhiy Storchaka7a0630c2019-04-08 14:34:04 +03001589
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001590* Removed ``__str__`` implementations from builtin types :class:`bool`,
1591 :class:`int`, :class:`float`, :class:`complex` and few classes from
1592 the standard library. They now inherit ``__str__()`` from :class:`object`.
1593 As result, defining the ``__repr__()`` method in the subclass of these
barioddd6117c2019-09-27 20:01:33 +02001594 classes will affect their string representation.
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001595 (Contributed by Serhiy Storchaka in :issue:`36793`.)
1596
Michael Felt9d949f72019-04-12 16:15:32 +02001597* On AIX, :attr:`sys.platform` doesn't contain the major version anymore.
1598 It is always ``'aix'``, instead of ``'aix3'`` .. ``'aix7'``. Since
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001599 older Python versions include the version number, so it is recommended to
1600 always use ``sys.platform.startswith('aix')``.
Michael Felt9d949f72019-04-12 16:15:32 +02001601 (Contributed by M. Felt in :issue:`36588`.)
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001602
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001603* :c:func:`PyEval_AcquireLock` and :c:func:`PyEval_AcquireThread` now
1604 terminate the current thread if called while the interpreter is
1605 finalizing, making them consistent with :c:func:`PyEval_RestoreThread`,
1606 :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`. If this
Raymond Hettingera3291532019-10-13 23:32:03 -07001607 behavior is not desired, guard the call by checking :c:func:`_Py_IsFinalizing`
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001608 or :c:func:`sys.is_finalizing`.
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001609 (Contributed by Joannah Nanjekye in :issue:`36475`.)
1610
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001611
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001612Changes in the Python API
1613-------------------------
1614
Victor Stinner689830e2019-06-26 17:31:12 +02001615* The :func:`os.getcwdb` function now uses the UTF-8 encoding on Windows,
1616 rather than the ANSI code page: see :pep:`529` for the rationale. The
1617 function is no longer deprecated on Windows.
1618 (Contributed by Victor Stinner in :issue:`37412`.)
1619
Victor Stinnerd7befad2019-04-25 14:30:16 +02001620* :class:`subprocess.Popen` can now use :func:`os.posix_spawn` in some cases
1621 for better performance. On Windows Subsystem for Linux and QEMU User
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001622 Emulation, the :class:`Popen` constructor using :func:`os.posix_spawn` no longer raises an
1623 exception on errors like "missing program". Instead the child process fails with a
Victor Stinnerd7befad2019-04-25 14:30:16 +02001624 non-zero :attr:`~Popen.returncode`.
Victor Stinner01ae8972019-06-03 16:28:01 +02001625 (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
Victor Stinnerd7befad2019-04-25 14:30:16 +02001626
Christian Heimes98d90f72019-08-27 23:36:56 +02001627* The *preexec_fn* argument of * :class:`subprocess.Popen` is no longer
1628 compatible with subinterpreters. The use of the parameter in a
1629 subinterpreter now raises :exc:`RuntimeError`.
1630 (Contributed by Eric Snow in :issue:`34651`, modified by Christian Heimes
1631 in :issue:`37951`.)
1632
Victor Stinner74125a62019-04-15 18:23:20 +02001633* The :meth:`imap.IMAP4.logout` method no longer ignores silently arbitrary
1634 exceptions.
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001635 (Contributed by Victor Stinner in :issue:`36348`.)
Victor Stinner74125a62019-04-15 18:23:20 +02001636
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001637* The function :func:`platform.popen` has been removed, after having been deprecated since
Victor Stinner73104fa2018-11-29 09:58:20 +01001638 Python 3.3: use :func:`os.popen` instead.
Victor Stinner01ae8972019-06-03 16:28:01 +02001639 (Contributed by Victor Stinner in :issue:`35345`.)
Victor Stinner73104fa2018-11-29 09:58:20 +01001640
Raymond Hettingerfc06a192019-03-12 00:43:27 -07001641* The :func:`statistics.mode` function no longer raises an exception
1642 when given multimodal data. Instead, it returns the first mode
1643 encountered in the input data. (Contributed by Raymond Hettinger
1644 in :issue:`35892`.)
1645
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001646* The :meth:`~tkinter.ttk.Treeview.selection` method of the
1647 :class:`tkinter.ttk.Treeview` class no longer takes arguments. Using it with
1648 arguments for changing the selection was deprecated in Python 3.6. Use
1649 specialized methods like :meth:`~tkinter.ttk.Treeview.selection_set` for
1650 changing the selection. (Contributed by Serhiy Storchaka in :issue:`31508`.)
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +02001651
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001652* The :meth:`writexml`, :meth:`toxml` and :meth:`toprettyxml` methods of
1653 :mod:`xml.dom.minidom`, and the :meth:`write` method of :mod:`xml.etree`,
1654 now preserve the attribute order specified by the user.
Diego Rojas06e1e682019-03-16 18:44:56 -05001655 (Contributed by Diego Rojas and Raymond Hettinger in :issue:`34160`.)
1656
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +02001657* A :mod:`dbm.dumb` database opened with flags ``'r'`` is now read-only.
1658 :func:`dbm.dumb.open` with flags ``'r'`` and ``'w'`` no longer creates
1659 a database if it does not exist.
1660 (Contributed by Serhiy Storchaka in :issue:`32749`.)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001661
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001662* The ``doctype()`` method defined in a subclass of
1663 :class:`~xml.etree.ElementTree.XMLParser` will no longer be called and will
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001664 emit a :exc:`RuntimeWarning` instead of a :exc:`DeprecationWarning`.
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001665 Define the :meth:`doctype() <xml.etree.ElementTree.TreeBuilder.doctype>`
1666 method on a target for handling an XML doctype declaration.
1667 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1668
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +03001669* A :exc:`RuntimeError` is now raised when the custom metaclass doesn't
1670 provide the ``__classcell__`` entry in the namespace passed to
1671 ``type.__new__``. A :exc:`DeprecationWarning` was emitted in Python
1672 3.6--3.7. (Contributed by Serhiy Storchaka in :issue:`23722`.)
1673
Scott Sandersoncebe80b2018-06-07 05:46:42 -04001674* The :class:`cProfile.Profile` class can now be used as a context
1675 manager. (Contributed by Scott Sanderson in :issue:`29235`.)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001676
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07001677* :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
1678 :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
1679 "fast-copy" syscalls (see
1680 :ref:`shutil-platform-dependent-efficient-copy-operations` section).
1681
1682* :func:`shutil.copyfile` default buffer size on Windows was changed from
1683 16 KiB to 1 MiB.
1684
Raymond Hettinger4f9ffc92019-08-05 13:33:19 -07001685* The ``PyGC_Head`` struct has changed completely. All code that touched the
Hugo van Kemenade547c60c2019-10-12 20:53:36 +03001686 struct member should be rewritten. (See :issue:`33597`.)
INADA Naokid5c875b2018-07-11 17:42:49 +09001687
Eric Snowbe3b2952019-02-23 11:35:52 -07001688* The ``PyInterpreterState`` struct has been moved into the "internal"
1689 header files (specifically Include/internal/pycore_pystate.h). An
1690 opaque ``PyInterpreterState`` is still available as part of the public
1691 API (and stable ABI). The docs indicate that none of the struct's
1692 fields are public, so we hope no one has been using them. However,
1693 if you do rely on one or more of those private fields and have no
1694 alternative then please open a BPO issue. We'll work on helping
1695 you adjust (possibly including adding accessor functions to the
1696 public API). (See :issue:`35886`.)
1697
Alex Grönholmcca4eec2018-08-09 00:06:47 +03001698* Asyncio tasks can now be named, either by passing the ``name`` keyword
1699 argument to :func:`asyncio.create_task` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001700 the :meth:`~asyncio.loop.create_task` event loop method, or by
Alex Grönholmcca4eec2018-08-09 00:06:47 +03001701 calling the :meth:`~asyncio.Task.set_name` method on the task object. The
1702 task name is visible in the ``repr()`` output of :class:`asyncio.Task` and
1703 can also be retrieved using the :meth:`~asyncio.Task.get_name` method.
1704
Berker Peksage7d4b2f2018-08-22 21:21:05 +03001705* The :meth:`mmap.flush() <mmap.mmap.flush>` method now returns ``None`` on
1706 success and raises an exception on error under all platforms. Previously,
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001707 its behavior was platform-dependent: a nonzero value was returned on success;
Berker Peksage7d4b2f2018-08-22 21:21:05 +03001708 zero was returned on error under Windows. A zero value was returned on
1709 success; an exception was raised on error under Unix.
1710 (Contributed by Berker Peksag in :issue:`2122`.)
1711
Andrés Delfinoca682612018-11-07 14:29:14 -03001712* :mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
Christian Heimes17b1d5d2018-09-23 09:50:25 +02001713 external entities by default.
1714 (Contributed by Christian Heimes in :issue:`17239`.)
INADA Naokid5c875b2018-07-11 17:42:49 +09001715
Xiang Zhang4fb0b8b2018-12-12 20:46:55 +08001716* Deleting a key from a read-only :mod:`dbm` database (:mod:`dbm.dumb`,
1717 :mod:`dbm.gnu` or :mod:`dbm.ndbm`) raises :attr:`error` (:exc:`dbm.dumb.error`,
1718 :exc:`dbm.gnu.error` or :exc:`dbm.ndbm.error`) instead of :exc:`KeyError`.
1719 (Contributed by Xiang Zhang in :issue:`33106`.)
1720
Steve Dower8ef864d2019-03-12 15:15:26 -07001721* :func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
1722 environment variable and does not use :envvar:`HOME`, which is not normally
1723 set for regular user accounts.
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001724 (Contributed by Anthony Sottile in :issue:`36264`.)
Steve Dower8ef864d2019-03-12 15:15:26 -07001725
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001726* The exception :class:`asyncio.CancelledError` now inherits from
Phil Jonese634da22019-10-12 17:46:13 +00001727 :class:`BaseException` rather than a :class:`Exception`.
1728 (Contributed by Yury Selivanov in :issue:`13528`.)
1729
Steve Dower2438cdf2019-03-29 16:37:16 -07001730.. _bpo-36085-whatsnew:
1731
1732* DLL dependencies for extension modules and DLLs loaded with :mod:`ctypes` on
1733 Windows are now resolved more securely. Only the system paths, the directory
1734 containing the DLL or PYD file, and directories added with
1735 :func:`~os.add_dll_directory` are searched for load-time dependencies.
1736 Specifically, :envvar:`PATH` and the current working directory are no longer
1737 used, and modifications to these will no longer have any effect on normal DLL
1738 resolution. If your application relies on these mechanisms, you should check
1739 for :func:`~os.add_dll_directory` and if it exists, use it to add your DLLs
Steve Dower79da3882019-03-30 20:58:17 -07001740 directory while loading your library. Note that Windows 7 users will need to
1741 ensure that Windows Update KB2533625 has been installed (this is also verified
1742 by the installer).
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001743 (Contributed by Steve Dower in :issue:`36085`.)
Steve Dower2438cdf2019-03-29 16:37:16 -07001744
Pablo Galindof2cf1e32019-04-13 17:05:14 +01001745* The header files and functions related to pgen have been removed after its
1746 replacement by a pure Python implementation. (Contributed by Pablo Galindo
1747 in :issue:`36623`.)
1748
Pablo Galindo5d23e282019-05-12 22:45:52 +01001749* :class:`types.CodeType` has a new parameter in the second position of the
1750 constructor (*posonlyargcount*) to support positional-only arguments defined
Pablo Galindocd74e662019-06-01 18:08:04 +01001751 in :pep:`570`. The first argument (*argcount*) now represents the total
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001752 number of positional arguments (including positional-only arguments). The new
Pablo Galindocd74e662019-06-01 18:08:04 +01001753 ``replace()`` method of :class:`types.CodeType` can be used to make the code
1754 future-proof.
Pablo Galindo5d23e282019-05-12 22:45:52 +01001755
Xiang Zhang4fb0b8b2018-12-12 20:46:55 +08001756
Inada Naokid3c72a22019-03-23 21:04:40 +09001757Changes in the C API
1758--------------------
1759
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001760* The :c:type:`PyCompilerFlags` structure got a new *cf_feature_version*
Victor Stinner2c9b4982019-06-13 02:01:29 +02001761 field. It should be initialized to ``PY_MINOR_VERSION``. The field is ignored
Andrew Kuchlingbb78f6c2019-10-13 11:51:36 -04001762 by default, and is used if and only if ``PyCF_ONLY_AST`` flag is set in
Victor Stinner2c9b4982019-06-13 02:01:29 +02001763 *cf_flags*.
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001764 (Contributed by Guido van Rossum in :issue:`35766`.)
Victor Stinner2c9b4982019-06-13 02:01:29 +02001765
Victor Stinnerd5d9e812019-05-13 12:35:37 +02001766* The :c:func:`PyEval_ReInitThreads` function has been removed from the C API.
1767 It should not be called explicitly: use :c:func:`PyOS_AfterFork_Child`
1768 instead.
1769 (Contributed by Victor Stinner in :issue:`36728`.)
1770
E. M. Brayc994c8f2019-05-24 17:33:47 +02001771* On Unix, C extensions are no longer linked to libpython except on Android
1772 and Cygwin. When Python is embedded, ``libpython`` must not be loaded with
xdegaye254b3092019-04-29 09:27:40 +02001773 ``RTLD_LOCAL``, but ``RTLD_GLOBAL`` instead. Previously, using
E. M. Brayc994c8f2019-05-24 17:33:47 +02001774 ``RTLD_LOCAL``, it was already not possible to load C extensions which
1775 were not linked to ``libpython``, like C extensions of the standard
1776 library built by the ``*shared*`` section of ``Modules/Setup``.
Victor Stinner01ae8972019-06-03 16:28:01 +02001777 (Contributed by Victor Stinner in :issue:`21536`.)
Victor Stinner8c3ecc62019-04-25 20:13:10 +02001778
Inada Naokid3c72a22019-03-23 21:04:40 +09001779* Use of ``#`` variants of formats in parsing or building value (e.g.
1780 :c:func:`PyArg_ParseTuple`, :c:func:`Py_BuildValue`, :c:func:`PyObject_CallFunction`,
1781 etc.) without ``PY_SSIZE_T_CLEAN`` defined raises ``DeprecationWarning`` now.
1782 It will be removed in 3.10 or 4.0. Read :ref:`arg-parsing` for detail.
1783 (Contributed by Inada Naoki in :issue:`36381`.)
1784
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001785* Instances of heap-allocated types (such as those created with
1786 :c:func:`PyType_FromSpec`) hold a reference to their type object.
1787 Increasing the reference count of these type objects has been moved from
1788 :c:func:`PyType_GenericAlloc` to the more low-level functions,
1789 :c:func:`PyObject_Init` and :c:func:`PyObject_INIT`.
1790 This makes types created through :c:func:`PyType_FromSpec` behave like
1791 other classes in managed code.
1792
1793 Statically allocated types are not affected.
1794
1795 For the vast majority of cases, there should be no side effect.
1796 However, types that manually increase the reference count after allocating
1797 an instance (perhaps to work around the bug) may now become immortal.
1798 To avoid this, these classes need to call Py_DECREF on the type object
1799 during instance deallocation.
1800
1801 To correctly port these types into 3.8, please apply the following
1802 changes:
1803
1804 * Remove :c:macro:`Py_INCREF` on the type object after allocating an
1805 instance - if any.
1806 This may happen after calling :c:func:`PyObject_New`,
1807 :c:func:`PyObject_NewVar`, :c:func:`PyObject_GC_New`,
1808 :c:func:`PyObject_GC_NewVar`, or any other custom allocator that uses
1809 :c:func:`PyObject_Init` or :c:func:`PyObject_INIT`.
1810
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001811 Example:
1812
1813 .. code-block:: c
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001814
1815 static foo_struct *
1816 foo_new(PyObject *type) {
1817 foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
1818 if (foo == NULL)
1819 return NULL;
1820 #if PY_VERSION_HEX < 0x03080000
1821 // Workaround for Python issue 35810; no longer necessary in Python 3.8
1822 PY_INCREF(type)
1823 #endif
1824 return foo;
1825 }
1826
1827 * Ensure that all custom ``tp_dealloc`` functions of heap-allocated types
1828 decrease the type's reference count.
1829
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001830 Example:
1831
1832 .. code-block:: c
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001833
1834 static void
1835 foo_dealloc(foo_struct *instance) {
1836 PyObject *type = Py_TYPE(instance);
1837 PyObject_GC_Del(instance);
1838 #if PY_VERSION_HEX >= 0x03080000
1839 // This was not needed before Python 3.8 (Python issue 35810)
1840 Py_DECREF(type);
1841 #endif
1842 }
1843
1844 (Contributed by Eddie Elizondo in :issue:`35810`.)
1845
Zackery Spytz3c8724f2019-05-28 09:16:33 -06001846* The :c:macro:`Py_DEPRECATED()` macro has been implemented for MSVC.
1847 The macro now must be placed before the symbol name.
1848
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001849 Example:
1850
1851 .. code-block:: c
Zackery Spytz3c8724f2019-05-28 09:16:33 -06001852
1853 Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
1854
1855 (Contributed by Zackery Spytz in :issue:`33407`.)
1856
Antoine Pitrouada319b2019-05-29 22:12:38 +02001857* The interpreter does not pretend to support binary compatibility of
Xtreak0d702272019-06-03 04:42:33 +05301858 extension types across feature releases, anymore. A :c:type:`PyTypeObject`
Antoine Pitrouada319b2019-05-29 22:12:38 +02001859 exported by a third-party extension module is supposed to have all the
1860 slots expected in the current Python version, including
1861 :c:member:`~PyTypeObject.tp_finalize` (:const:`Py_TPFLAGS_HAVE_FINALIZE`
1862 is not checked anymore before reading :c:member:`~PyTypeObject.tp_finalize`).
1863
1864 (Contributed by Antoine Pitrou in :issue:`32388`.)
1865
Pablo Galindo545a3b82019-05-31 19:33:41 +01001866* The :c:func:`PyCode_New` has a new parameter in the second position (*posonlyargcount*)
1867 to support :pep:`570`, indicating the number of positional-only arguments.
1868
Ivan Levkivskyi47c2de72019-06-19 01:17:47 +01001869* The functions :c:func:`PyNode_AddChild` and :c:func:`PyParser_AddToken` now accept
1870 two additional ``int`` arguments *end_lineno* and *end_col_offset*.
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001871
Steve Dowerf5690922019-06-21 14:28:46 -07001872* The :file:`libpython38.a` file to allow MinGW tools to link directly against
1873 :file:`python38.dll` is no longer included in the regular Windows distribution.
1874 If you require this file, it may be generated with the ``gendef`` and
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001875 ``dlltool`` tools, which are part of the MinGW binutils package:
1876
1877 .. code-block:: shell
Steve Dowerf5690922019-06-21 14:28:46 -07001878
1879 gendef python38.dll > tmp.def
1880 dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a
1881
1882 The location of an installed :file:`pythonXY.dll` will depend on the
1883 installation options and the version and language of Windows. See
1884 :ref:`using-on-windows` for more information. The resulting library should be
1885 placed in the same directory as :file:`pythonXY.lib`, which is generally the
1886 :file:`libs` directory under your Python installation.
1887
Serhiy Storchaka298439c2019-10-14 16:10:40 +03001888 (Contributed by Steve Dower in :issue:`37351`.)
Steve Dowerf5690922019-06-21 14:28:46 -07001889
1890
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001891CPython bytecode changes
1892------------------------
1893
1894* The interpreter loop has been simplified by moving the logic of unrolling
1895 the stack of blocks into the compiler. The compiler emits now explicit
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +02001896 instructions for adjusting the stack of values and calling the
1897 cleaning-up code for :keyword:`break`, :keyword:`continue` and
1898 :keyword:`return`.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001899
1900 Removed opcodes :opcode:`BREAK_LOOP`, :opcode:`CONTINUE_LOOP`,
1901 :opcode:`SETUP_LOOP` and :opcode:`SETUP_EXCEPT`. Added new opcodes
1902 :opcode:`ROT_FOUR`, :opcode:`BEGIN_FINALLY`, :opcode:`CALL_FINALLY` and
1903 :opcode:`POP_FINALLY`. Changed the behavior of :opcode:`END_FINALLY`
1904 and :opcode:`WITH_CLEANUP_START`.
1905
1906 (Contributed by Mark Shannon, Antoine Pitrou and Serhiy Storchaka in
1907 :issue:`17611`.)
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001908
1909* Added new opcode :opcode:`END_ASYNC_FOR` for handling exceptions raised
1910 when awaiting a next item in an :keyword:`async for` loop.
1911 (Contributed by Serhiy Storchaka in :issue:`33041`.)
Raymond Hettingerf75d59e2019-02-02 22:54:56 -08001912
Pablo Galindob51b7132019-06-25 02:41:58 +01001913* The :opcode:`MAP_ADD` now expects the value as the first element in the
1914 stack and the key as the second element. This change was made so the key
1915 is always evaluated before the value in dictionary comprehensions, as
Pablo Galindode9b6062019-06-25 11:55:23 +01001916 proposed by :pep:`572`. (Contributed by Jörn Heissler in :issue:`35224`.)
Pablo Galindob51b7132019-06-25 02:41:58 +01001917
Raymond Hettingerf75d59e2019-02-02 22:54:56 -08001918
1919Demos and Tools
1920---------------
1921
1922* Added a benchmark script for timing various ways to access variables:
1923 ``Tools/scripts/var_access_benchmark.py``.
1924 (Contributed by Raymond Hettinger in :issue:`35884`.)