blob: 264586434b9b0866c54b24f1e66c28767329c23b [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
42 This saves the maintainer the effort of going through the Mercurial log
43 when researching a change.
44
45This article explains the new features in Python 3.8, compared to 3.7.
46
Ned Deily45ab51c2018-02-28 13:58:38 -050047For full details, see the :ref:`changelog <changelog>`.
Ned Deily07a18922018-01-31 18:12:38 -050048
49.. note::
50
51 Prerelease users should be aware that this document is currently in draft
52 form. It will be updated substantially as Python 3.8 moves towards release,
53 so it's worth checking back even after reading earlier versions.
54
Nick Coghlanb9438ce2019-06-09 19:07:42 +100055 Some notable items not yet covered here:
56
Nick Coghlanb9438ce2019-06-09 19:07:42 +100057 * :pep:`578` - Runtime audit hooks for potentially sensitive operations
58 * ``python -m asyncio`` runs a natively async REPL
59 * ...
60
Ned Deily07a18922018-01-31 18:12:38 -050061
62Summary -- Release highlights
63=============================
64
65.. This section singles out the most important changes in Python 3.8.
66 Brevity is key.
67
68
69.. PEP-sized items next.
70
71
72
73New Features
74============
75
Guido van Rossum09d434c2019-04-24 11:30:17 -070076Assignment expressions
77----------------------
78
79There is new syntax (the "walrus operator", ``:=``) to assign values
80to variables as part of an expression. Example::
81
82 if (n := len(a)) > 10:
83 print(f"List is too long ({n} elements, expected <= 10)")
84
85See :pep:`572` for a full description.
86
87(Contributed by Emily Morehouse in :issue:`35224`.)
88
89.. TODO: Emily will sprint on docs at PyCon US 2019.
90
91
Guido van Rossum843bf422019-04-29 05:49:30 -070092Positional-only parameters
93--------------------------
94
95There is new syntax (``/``) to indicate that some function parameters
96must be specified positionally (i.e., cannot be used as keyword
97arguments). This is the same notation as shown by ``help()`` for
98functions implemented in C (produced by Larry Hastings' "Argument
99Clinic" tool). Example::
100
101 def pow(x, y, z=None, /):
102 r = x**y
103 if z is not None:
104 r %= z
105 return r
106
107Now ``pow(2, 10)`` and ``pow(2, 10, 17)`` are valid calls, but
108``pow(x=2, y=10)`` and ``pow(2, 10, z=17)`` are invalid.
109
110See :pep:`570` for a full description.
111
112(Contributed by Pablo Galindo in :issue:`36540`.)
113
114.. TODO: Pablo will sprint on docs at PyCon US 2019.
115
116
Nick Coghlan16eb3bc2018-06-20 21:25:01 +1000117Parallel filesystem cache for compiled bytecode files
118-----------------------------------------------------
119
120The new :envvar:`PYTHONPYCACHEPREFIX` setting (also available as
121:option:`-X` ``pycache_prefix``) configures the implicit bytecode
122cache to use a separate parallel filesystem tree, rather than
123the default ``__pycache__`` subdirectories within each source
124directory.
125
126The location of the cache is reported in :data:`sys.pycache_prefix`
127(:const:`None` indicates the default location in ``__pycache__``
128subdirectories).
129
130(Contributed by Carl Meyer in :issue:`33499`.)
Ned Deily07a18922018-01-31 18:12:38 -0500131
Victor Stinner40460692019-04-26 17:56:44 +0200132Debug build uses the same ABI as release build
133-----------------------------------------------
134
Paul Ganssle5c403b22019-04-27 14:14:35 -0400135Python now uses the same ABI whether it built in release or debug mode. On
136Unix, when Python is built in debug mode, it is now possible to load C
137extensions built in release mode and C extensions built using the stable ABI.
Victor Stinner40460692019-04-26 17:56:44 +0200138
Paul Ganssle5c403b22019-04-27 14:14:35 -0400139Release builds and debug builds are now ABI compatible: defining the
140``Py_DEBUG`` macro no longer implies the ``Py_TRACE_REFS`` macro, which
141introduces the only ABI incompatibility. The ``Py_TRACE_REFS`` macro, which
142adds the :func:`sys.getobjects` function and the :envvar:`PYTHONDUMPREFS`
143environment variable, can be set using the new ``./configure --with-trace-refs``
144build option.
Victor Stinner40460692019-04-26 17:56:44 +0200145(Contributed by Victor Stinner in :issue:`36465`.)
146
E. M. Brayc994c8f2019-05-24 17:33:47 +0200147On Unix, C extensions are no longer linked to libpython except on Android
148and Cygwin.
Victor Stinner4ebcd7e2019-05-11 04:10:03 +0200149It is now possible
Paul Ganssle5c403b22019-04-27 14:14:35 -0400150for a statically linked Python to load a C extension built using a shared
151library Python.
Victor Stinner40460692019-04-26 17:56:44 +0200152(Contributed by Victor Stinner in :issue:`21536`.)
153
154On Unix, when Python is built in debug mode, import now also looks for C
155extensions compiled in release mode and for C extensions compiled with the
156stable ABI.
157(Contributed by Victor Stinner in :issue:`36722`.)
158
Victor Stinner0a8e5722019-05-23 03:30:23 +0200159To embed Python into an application, a new ``--embed`` option must be passed to
160``python3-config --libs --embed`` to get ``-lpython3.8`` (link the application
161to libpython). To support both 3.8 and older, try ``python3-config --libs
162--embed`` first and fallback to ``python3-config --libs`` (without ``--embed``)
163if the previous command fails.
164
165Add a pkg-config ``python-3.8-embed`` module to embed Python into an
166application: ``pkg-config python-3.8-embed --libs`` includes ``-lpython3.8``.
167To support both 3.8 and older, try ``pkg-config python-X.Y-embed --libs`` first
168and fallback to ``pkg-config python-X.Y --libs`` (without ``--embed``) if the
169previous command fails (replace ``X.Y`` with the Python version).
170
171On the other hand, ``pkg-config python3.8 --libs`` no longer contains
172``-lpython3.8``. C extensions must not be linked to libpython (except on
E. M. Brayc994c8f2019-05-24 17:33:47 +0200173Android and Cygwin, whose cases are handled by the script);
174this change is backward incompatible on purpose.
Victor Stinner0a8e5722019-05-23 03:30:23 +0200175(Contributed by Victor Stinner in :issue:`36721`.)
176
Eric V. Smith9a4135e2019-05-08 16:28:48 -0400177f-strings now support = for quick and easy debugging
178-----------------------------------------------------
179
180Add ``=`` specifier to f-strings. ``f'{expr=}'`` expands
181to the text of the expression, an equal sign, then the repr of the
182evaluated expression. So::
183
184 x = 3
185 print(f'{x*9 + 15=}')
186
187Would print ``x*9 + 15=42``.
188
189(Contributed by Eric V. Smith and Larry Hastings in :issue:`36817`.)
190
Victor Stinner331a6a52019-05-27 16:39:22 +0200191PEP 587: Python Initialization Configuration
192--------------------------------------------
193
194The :pep:`587` adds a new C API to configure the Python Initialization
195providing finer control on the whole configuration and better error reporting.
196
197New structures:
198
199* :c:type:`PyConfig`
200* :c:type:`PyPreConfig`
201* :c:type:`PyStatus`
202* :c:type:`PyWideStringList`
203
204New functions:
205
206* :c:func:`PyConfig_Clear`
207* :c:func:`PyConfig_InitIsolatedConfig`
208* :c:func:`PyConfig_InitPythonConfig`
209* :c:func:`PyConfig_Read`
210* :c:func:`PyConfig_SetArgv`
211* :c:func:`PyConfig_SetBytesArgv`
212* :c:func:`PyConfig_SetBytesString`
213* :c:func:`PyConfig_SetString`
214* :c:func:`PyPreConfig_InitIsolatedConfig`
215* :c:func:`PyPreConfig_InitPythonConfig`
216* :c:func:`PyStatus_Error`
217* :c:func:`PyStatus_Exception`
218* :c:func:`PyStatus_Exit`
219* :c:func:`PyStatus_IsError`
220* :c:func:`PyStatus_IsExit`
221* :c:func:`PyStatus_NoMemory`
222* :c:func:`PyStatus_Ok`
223* :c:func:`PyWideStringList_Append`
224* :c:func:`PyWideStringList_Insert`
225* :c:func:`Py_BytesMain`
226* :c:func:`Py_ExitStatusException`
227* :c:func:`Py_InitializeFromConfig`
228* :c:func:`Py_PreInitialize`
229* :c:func:`Py_PreInitializeFromArgs`
230* :c:func:`Py_PreInitializeFromBytesArgs`
231* :c:func:`Py_RunMain`
232
233This PEP also adds ``_PyRuntimeState.preconfig`` (:c:type:`PyPreConfig` type)
234and ``PyInterpreterState.config`` (:c:type:`PyConfig` type) fields to these
235internal structures. ``PyInterpreterState.config`` becomes the new
236reference configuration, replacing global configuration variables and
237other private variables.
238
239See :ref:`Python Initialization Configuration <init-config>` for the
240documentation.
241
242See :pep:`587` for a full description.
243
244(Contributed by Victor Stinner in :issue:`36763`.)
245
Ned Deily07a18922018-01-31 18:12:38 -0500246
Jeroen Demeyer9e3e06e2019-06-03 01:43:13 +0200247Vectorcall: a fast calling protocol for CPython
248-----------------------------------------------
249
250The "vectorcall" protocol is added to the Python/C API.
251It is meant to formalize existing optimizations which were already done
252for various classes.
253Any extension type implementing a callable can use this protocol.
254
255This is currently provisional,
256the aim is to make it fully public in Python 3.9.
257
258See :pep:`590` for a full description.
259
260(Contributed by Jeroen Demeyer and Mark Shannon in :issue:`36974`.)
261
262
Antoine Pitrouc879ff22019-06-09 14:47:15 +0200263Pickle protocol 5 with out-of-band data buffers
264-----------------------------------------------
265
266When :mod:`pickle` is used to transfer large data between Python processes
267in order to take advantage of multi-core or multi-machine processing,
268it is important to optimize the transfer by reducing memory copies, and
269possibly by applying custom techniques such as data-dependent compression.
270
271The :mod:`pickle` protocol 5 introduces support for out-of-band buffers
272where :pep:`3118`-compatible data can be transmitted separately from the
273main pickle stream, at the discretion of the communication layer.
274
275See :pep:`574` for a full description.
276
277(Contributed by Antoine Pitrou in :issue:`36785`.)
278
279
Ned Deily07a18922018-01-31 18:12:38 -0500280Other Language Changes
281======================
282
Serhiy Storchakafe2bbb12018-03-18 09:56:52 +0200283* A :keyword:`continue` statement was illegal in the :keyword:`finally` clause
284 due to a problem with the implementation. In Python 3.8 this restriction
285 was lifted.
286 (Contributed by Serhiy Storchaka in :issue:`32489`.)
287
Serhiy Storchakab2e20252018-10-20 00:46:31 +0300288* The :class:`int` type now has a new :meth:`~int.as_integer_ratio` method
289 compatible with the existing :meth:`float.as_integer_ratio` method.
Lisa Roach5ac70432018-09-13 23:56:23 -0700290 (Contributed by Lisa Roach in :issue:`33073`.)
291
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300292* Constructors of :class:`int`, :class:`float` and :class:`complex` will now
293 use the :meth:`~object.__index__` special method, if available and the
294 corresponding method :meth:`~object.__int__`, :meth:`~object.__float__`
295 or :meth:`~object.__complex__` is not available.
296 (Contributed by Serhiy Storchaka in :issue:`20092`.)
297
Serhiy Storchakaa445feb2018-02-10 00:08:17 +0200298* Added support of ``\N{name}`` escapes in :mod:`regular expressions <re>`.
299 (Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.)
Ned Deily07a18922018-01-31 18:12:38 -0500300
Rémi Lapeyre6531bf62018-11-06 01:38:54 +0100301* Dict and dictviews are now iterable in reversed insertion order using
302 :func:`reversed`. (Contributed by Rémi Lapeyre in :issue:`33462`.)
303
Benjamin Petersonc9a71dd2018-09-12 17:14:39 -0700304* The syntax allowed for keyword names in function calls was further
305 restricted. In particular, ``f((keyword)=arg)`` is no longer allowed. It was
306 never intended to permit more than a bare name on the left-hand side of a
307 keyword argument assignment term. See :issue:`34641`.
Ned Deily07a18922018-01-31 18:12:38 -0500308
jChapman8fabae32018-09-22 21:13:10 -0400309* Iterable unpacking is now allowed without parentheses in :keyword:`yield`
310 and :keyword:`return` statements.
311 (Contributed by David Cuthbert and Jordan Chapman in :issue:`32117`.)
312
Serhiy Storchaka65439122018-10-19 17:42:06 +0300313* A backslash-character pair that is not a valid escape sequence generates
314 a :exc:`DeprecationWarning` since Python 3.6. In Python 3.8 it generates
315 a :exc:`SyntaxWarning` instead.
316 (Contributed by Serhiy Storchaka in :issue:`32912`.)
317
Serhiy Storchaka62e44812019-02-16 08:12:19 +0200318* The compiler now produces a :exc:`SyntaxWarning` in some cases when a comma
319 is missed before tuple or list. For example::
320
321 data = [
322 (1, 2, 3) # oops, missing comma!
323 (4, 5, 6)
324 ]
325
326 (Contributed by Serhiy Storchaka in :issue:`15248`.)
327
Paul Ganssled9503c32019-02-08 11:02:00 -0500328* Arithmetic operations between subclasses of :class:`datetime.date` or
329 :class:`datetime.datetime` and :class:`datetime.timedelta` objects now return
330 an instance of the subclass, rather than the base class. This also affects
331 the return type of operations whose implementation (directly or indirectly)
332 uses :class:`datetime.timedelta` arithmetic, such as
333 :meth:`datetime.datetime.astimezone`.
334 (Contributed by Paul Ganssle in :issue:`32417`.)
335
Gregory P. Smith06babb22019-02-23 10:43:49 -0800336* When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the
337 resulting :exc:`KeyboardInterrupt` exception is not caught, the Python process
338 now exits via a SIGINT signal or with the correct exit code such that the
339 calling process can detect that it died due to a Ctrl-C. Shells on POSIX
340 and Windows use this to properly terminate scripts in interactive sessions.
341 (Contributed by Google via Gregory P. Smith in :issue:`1054041`.)
342
Victor Stinnera9f05d62019-05-24 23:57:23 +0200343* Added new ``replace()`` method to the code type (:class:`types.CodeType`).
344 (Contributed by Victor Stinner in :issue:`37032`.)
345
Mark Dickinsonc5299672019-06-02 10:24:06 +0100346* For integers, the three-argument form of the :func:`pow` function now permits
347 the exponent to be negative in the case where the base is relatively prime to
348 the modulus. It then computes a modular inverse to the base when the exponent
349 is ``-1``, and a suitable power of that inverse for other negative exponents.
350 (Contributed by Mark Dickinson in :issue:`36027`.)
351
Serhiy Storchaka65439122018-10-19 17:42:06 +0300352
Ned Deily07a18922018-01-31 18:12:38 -0500353New Modules
354===========
355
Barry Warsaw4867eaa2019-06-05 19:40:19 -0700356* The new :mod:`importlib.metadata` module provides (provisional) support for
357 reading metadata from third-party packages. For example, you can extract an
358 installed package's version number, list of entry points, and more. See
359 :issue:`34632` for additional details.
Ned Deily07a18922018-01-31 18:12:38 -0500360
361
362Improved Modules
363================
364
Raymond Hettinger0bb4bdf2019-01-31 00:59:50 -0800365
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700366ast
367---
368
369AST nodes now have ``end_lineno`` and ``end_col_offset`` attributes,
370which give the precise location of the end of the node. (This only
371applies to nodes that have ``lineno`` and ``col_offset`` attributes.)
372
373The :func:`ast.parse` function has some new flags:
374
375* ``type_comments=True`` causes it to return the text of :pep:`484` and
376 :pep:`526` type comments associated with certain AST nodes;
377
378* ``mode='func_type'`` can be used to parse :pep:`484` "signature type
379 comments" (returned for function definition AST nodes);
380
Guido van Rossum10b55c12019-06-11 17:23:12 -0700381* ``feature_version=(3, N)`` allows specifying an earlier Python 3
382 version. (For example, ``feature_version=(3, 4)`` will treat
383 ``async`` and ``await`` as non-reserved words.)
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700384
385New function :func:`ast.get_source_segment` returns the source code
386for a specific AST node.
387
388
Victor Stinner6ea29c52018-09-25 08:27:08 -0700389asyncio
390-------
391
392On Windows, the default event loop is now :class:`~asyncio.ProactorEventLoop`.
Victor Stinner01ae8972019-06-03 16:28:01 +0200393(Contributed by Victor Stinner in :issue:`34687`.)
394
395:class:`~asyncio.ProactorEventLoop` now also supports UDP.
396(Contributed by Adam Meily and Andrew Svetlov in :issue:`29883`.)
397
398:class:`~asyncio.ProactorEventLoop` can now be interrupted by
399:exc:`KeyboardInterrupt` ("CTRL+C").
400(Contributed by Vladimir Matveev in :issue:`23057`.)
401
Victor Stinner6ea29c52018-09-25 08:27:08 -0700402
Matthias Bussonnier2ddbd212019-05-22 12:07:45 -0700403builtins
404--------
405
406The :func:`compile` built-in has been improved to accept the
407``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` flag. With this new flag passed,
408:func:`compile` will allow top-level ``await``, ``async for`` and ``async with``
409constructs that are usually considered invalid syntax. Asynchronous code object
410marked with the ``CO_COROUTINE`` flag may then be returned.
411
412(Contributed by Matthias Bussonnier in :issue:`34616`)
Terry Jan Reedyfdcb5ae2018-09-25 12:45:27 -0400413
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700414collections
415-----------
416
417The :meth:`_asdict()` method for :func:`collections.namedtuple` now returns
Daniel Porteous05222912019-05-02 04:20:59 -0400418a :class:`dict` instead of a :class:`collections.OrderedDict`. This works because
419regular dicts have guaranteed ordering since Python 3.7. If the extra
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700420features of :class:`OrderedDict` are required, the suggested remediation is
421to cast the result to the desired type: ``OrderedDict(nt._asdict())``.
422(Contributed by Raymond Hettinger in :issue:`35864`.)
423
424
Steve Dower2438cdf2019-03-29 16:37:16 -0700425ctypes
426------
427
428On Windows, :class:`~ctypes.CDLL` and subclasses now accept a *winmode* parameter
429to specify flags for the underlying ``LoadLibraryEx`` call. The default flags are
430set to only load DLL dependencies from trusted locations, including the path
431where the DLL is stored (if a full or partial path is used to load the initial
432DLL) and paths added by :func:`~os.add_dll_directory`.
433
434
Raymond Hettingerb8218682019-05-26 11:27:35 -0700435functools
436---------
437
438:func:`functools.lru_cache` can now be used as a straight decorator rather
439than as a function returning a decorator. So both of these are now supported::
440
441 @lru_cache
442 def f(x):
443 ...
444
445 @lru_cache(maxsize=256)
446 def f(x):
447 ...
448
449(Contributed by Raymond Hettinger in :issue:`36772`.)
450
451
Paul Ganssle88c09372019-04-29 09:22:03 -0400452datetime
453--------
454
455Added new alternate constructors :meth:`datetime.date.fromisocalendar` and
456:meth:`datetime.datetime.fromisocalendar`, which construct :class:`date` and
457:class:`datetime` objects respectively from ISO year, week number and weekday;
458these are the inverse of each class's ``isocalendar`` method.
459(Contributed by Paul Ganssle in :issue:`36004`.)
460
461
Cheryl Sabella637a33b2018-11-07 09:12:20 -0500462gettext
463-------
464
465Added :func:`~gettext.pgettext` and its variants.
466(Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in :issue:`2504`.)
467
Raymond Hettingerd1e768a2019-03-25 13:01:13 -0700468inspect
469-------
470
471The :func:`inspect.getdoc` function can now find docstrings for ``__slots__``
472if that attribute is a :class:`dict` where the values are docstrings.
473This provides documentation options similar to what we already have
474for :func:`property`, :func:`classmethod`, and :func:`staticmethod`::
475
476 class AudioClip:
477 __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
478 'duration': 'in seconds, rounded up to an integer'}
479 def __init__(self, bit_rate, duration):
480 self.bit_rate = round(bit_rate / 1000.0, 1)
481 self.duration = ceil(duration)
Pablo Galindo175421b2019-02-23 03:02:06 +0000482
Victor Stinnerbc2aa812019-05-23 03:45:09 +0200483io
484--
485
486In development mode (:option:`-X` ``env``) and in debug build, the
487:class:`io.IOBase` finalizer now logs the exception if the ``close()`` method
488fails. The exception is ignored silently by default in release build.
489(Contributed by Victor Stinner in :issue:`18748`.)
490
491
Pablo Galindo175421b2019-02-23 03:02:06 +0000492gc
493--
494
495:func:`~gc.get_objects` can now receive an optional *generation* parameter
496indicating a generation to get objects from. Contributed in
497:issue:`36016` by Pablo Galindo.
498
499
guoci0e7497c2018-11-07 04:50:23 -0500500gzip
501----
502
503Added the *mtime* parameter to :func:`gzip.compress` for reproducible output.
504(Contributed by Guo Ci Teo in :issue:`34898`.)
505
Zackery Spytzcf599f62019-05-13 01:50:52 -0600506A :exc:`~gzip.BadGzipFile` exception is now raised instead of :exc:`OSError`
507for certain types of invalid or corrupt gzip files.
508(Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in
509:issue:`6584`.)
510
guoci0e7497c2018-11-07 04:50:23 -0500511
Terry Jan Reedyfdcb5ae2018-09-25 12:45:27 -0400512idlelib and IDLE
513----------------
514
515Output over N lines (50 by default) is squeezed down to a button.
516N can be changed in the PyShell section of the General page of the
517Settings dialog. Fewer, but possibly extra long, lines can be squeezed by
518right clicking on the output. Squeezed output can be expanded in place
519by double-clicking the button or into the clipboard or a separate window
520by right-clicking the button. (Contributed by Tal Einat in :issue:`1529353`.)
521
522The changes above have been backported to 3.7 maintenance releases.
523
524
HongWeipengf1944792018-11-07 18:09:32 +0800525json.tool
526---------
527
528Add option ``--json-lines`` to parse every input line as separate JSON object.
529(Contributed by Weipeng Hong in :issue:`31553`.)
530
Pablo Galindobc098512019-02-07 07:04:02 +0000531
532math
533----
534
Raymond Hettinger3ff59622019-02-16 11:00:42 -0800535Added new function :func:`math.dist` for computing Euclidean distance
536between two points. (Contributed by Raymond Hettinger in :issue:`33089`.)
537
538Expanded the :func:`math.hypot` function to handle multiple dimensions.
539Formerly, it only supported the 2-D case.
540(Contributed by Raymond Hettinger in :issue:`33089`.)
541
Pablo Galindobc098512019-02-07 07:04:02 +0000542Added new function, :func:`math.prod`, as analogous function to :func:`sum`
543that returns the product of a 'start' value (default: 1) times an iterable of
Raymond Hettinger3ff59622019-02-16 11:00:42 -0800544numbers. (Contributed by Pablo Galindo in :issue:`35606`)
Pablo Galindobc098512019-02-07 07:04:02 +0000545
Mark Dickinson73934b92019-05-18 12:29:50 +0100546Added new function :func:`math.isqrt` for computing integer square roots.
547(Contributed by Mark Dickinson in :issue:`36887`.)
548
Mark Dickinsona0adffb2019-06-01 12:21:53 +0100549The function :func:`math.factorial` no longer accepts arguments that are not
550int-like. (Contributed by Pablo Galindo in :issue:`33083`.)
551
Zackery Spytz02db6962019-05-27 10:48:17 -0600552
553mmap
554----
555
556The :class:`mmap.mmap` class now has an :meth:`~mmap.mmap.madvise` method to
557access the ``madvise()`` system call.
558(Contributed by Zackery Spytz in :issue:`32941`.)
559
560
Victor Stinner17a55882019-05-28 16:02:50 +0200561multiprocessing
562---------------
563
564Added new :mod:`multiprocessing.shared_memory` module.
565(Contributed Davin Potts in :issue:`35813`.)
566
567On macOS, the *spawn* start method is now used by default.
568(Contributed by Victor Stinner in :issue:`33725`.)
569
570
Steve Dower2438cdf2019-03-29 16:37:16 -0700571os
572--
573
574Added new function :func:`~os.add_dll_directory` on Windows for providing
575additional search paths for native dependencies when importing extension
576modules or loading DLLs using :mod:`ctypes`.
577
Zackery Spytz43fdbd22019-05-29 13:57:07 -0600578A new :func:`os.memfd_create` function was added to wrap the
579``memfd_create()`` syscall.
580(Contributed by Zackery Spytz and Christian Heimes in :issue:`26836`.)
581
Pablo Galindobc098512019-02-07 07:04:02 +0000582
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300583os.path
584-------
585
586:mod:`os.path` functions that return a boolean result like
587:func:`~os.path.exists`, :func:`~os.path.lexists`, :func:`~os.path.isdir`,
588:func:`~os.path.isfile`, :func:`~os.path.islink`, and :func:`~os.path.ismount`
589now return ``False`` instead of raising :exc:`ValueError` or its subclasses
590:exc:`UnicodeEncodeError` and :exc:`UnicodeDecodeError` for paths that contain
591characters or bytes unrepresentable at the OS level.
592(Contributed by Serhiy Storchaka in :issue:`33721`.)
593
Steve Dower8ef864d2019-03-12 15:15:26 -0700594:func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
595environment variable and does not use :envvar:`HOME`, which is not normally set
596for regular user accounts.
597
Serhiy Storchakab232df92018-10-30 13:22:42 +0200598
599ncurses
600-------
601
602Added a new variable holding structured version information for the
603underlying ncurses library: :data:`~curses.ncurses_version`.
604(Contributed by Serhiy Storchaka in :issue:`31680`.)
605
606
Serhiy Storchaka0185f342018-09-18 11:28:51 +0300607pathlib
608-------
609
610:mod:`pathlib.Path` methods that return a boolean result like
611:meth:`~pathlib.Path.exists()`, :meth:`~pathlib.Path.is_dir()`,
612:meth:`~pathlib.Path.is_file()`, :meth:`~pathlib.Path.is_mount()`,
613:meth:`~pathlib.Path.is_symlink()`, :meth:`~pathlib.Path.is_block_device()`,
614:meth:`~pathlib.Path.is_char_device()`, :meth:`~pathlib.Path.is_fifo()`,
615:meth:`~pathlib.Path.is_socket()` now return ``False`` instead of raising
616:exc:`ValueError` or its subclass :exc:`UnicodeEncodeError` for paths that
617contain characters unrepresentable at the OS level.
618(Contributed by Serhiy Storchaka in :issue:`33721`.)
619
Joannah Nanjekye6b5b0132019-05-04 11:27:10 -0400620Added :meth:`pathlib.Path.link_to()` which creates a hard link pointing
621to a path.
622(Contributed by Joannah Nanjekye in :issue:`26978`)
623
jab9e00d9e2018-12-28 13:03:40 -0500624
Jon Janzenc981ad12019-05-15 22:14:38 +0200625plistlib
626--------
627
628Added new :class:`plistlib.UID` and enabled support for reading and writing
629NSKeyedArchiver-encoded binary plists.
630(Contributed by Jon Janzen in :issue:`26707`.)
631
632
Joannah Nanjekye2e33ecd2019-05-28 13:29:04 -0300633py_compile
634----------
635
636:func:`py_compile.compile` now supports silent mode.
637(Contributed by Joannah Nanjekye in :issue:`22640`.)
638
639
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +0200640socket
641------
642
643Added :meth:`~socket.create_server()` and :meth:`~socket.has_dualstack_ipv6()`
644convenience functions to automate the necessary tasks usually involved when
645creating a server socket, including accepting both IPv4 and IPv6 connections
646on the same socket. (Contributed by Giampaolo Rodola in :issue:`17561`.)
647
Zackery Spytz8f96c9f2019-05-29 15:02:37 -0600648The :func:`socket.if_nameindex()`, :func:`socket.if_nametoindex()`, and
649:func:`socket.if_indextoname()` functions have been implemented on Windows.
650(Contributed by Zackery Spytz in :issue:`37007`.)
651
Bo Baylesca804952019-05-29 03:06:12 -0500652shlex
653----------
654
655The new :func:`shlex.join` function acts as the inverse of :func:`shlex.split`.
656(Contributed by Bo Bayles in :issue:`32102`.)
Giampaolo Rodolaeb7e29f2019-04-09 00:34:02 +0200657
jab9e00d9e2018-12-28 13:03:40 -0500658shutil
659------
660
661:func:`shutil.copytree` now accepts a new ``dirs_exist_ok`` keyword argument.
662(Contributed by Josh Bronson in :issue:`20849`.)
663
CAM Gerlach89a89442019-04-06 23:47:49 -0500664:func:`shutil.make_archive` now defaults to the modern pax (POSIX.1-2001)
665format for new archives to improve portability and standards conformance,
666inherited from the corresponding change to the :mod:`tarfile` module.
667(Contributed by C.A.M. Gerlach in :issue:`30661`.)
668
jab9e00d9e2018-12-28 13:03:40 -0500669
Christian Heimes9fb051f2018-09-23 08:32:31 +0200670ssl
671---
672
673Added :attr:`SSLContext.post_handshake_auth` to enable and
674:meth:`ssl.SSLSocket.verify_client_post_handshake` to initiate TLS 1.3
675post-handshake authentication.
676(Contributed by Christian Heimes in :issue:`34670`.)
677
Raymond Hettinger47d99872019-02-21 15:06:29 -0800678
679statistics
680----------
681
682Added :func:`statistics.fmean` as a faster, floating point variant of
683:func:`statistics.mean()`. (Contributed by Raymond Hettinger and
684Steven D'Aprano in :issue:`35904`.)
685
Raymond Hettinger6463ba32019-04-07 09:20:03 -0700686Added :func:`statistics.geometric_mean()`
687(Contributed by Raymond Hettinger in :issue:`27181`.)
688
Raymond Hettingerfc06a192019-03-12 00:43:27 -0700689Added :func:`statistics.multimode` that returns a list of the most
690common values. (Contributed by Raymond Hettinger in :issue:`35892`.)
691
Raymond Hettinger9013ccf2019-04-23 00:06:35 -0700692Added :func:`statistics.quantiles` that divides data or a distribution
693in to equiprobable intervals (e.g. quartiles, deciles, or percentiles).
694(Contributed by Raymond Hettinger in :issue:`36546`.)
695
Raymond Hettinger11c79532019-02-23 14:44:07 -0800696Added :class:`statistics.NormalDist`, a tool for creating
697and manipulating normal distributions of a random variable.
698(Contributed by Raymond Hettinger in :issue:`36018`.)
699
700::
701
702 >>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
Raymond Hettinger671d7822019-05-01 17:49:12 -0700703 >>> temperature_feb.mean
704 6.0
705 >>> temperature_feb.stdev
706 6.356099432828281
Raymond Hettinger11c79532019-02-23 14:44:07 -0800707
708 >>> temperature_feb.cdf(3) # Chance of being under 3 degrees
709 0.3184678262814532
710 >>> # Relative chance of being 7 degrees versus 10 degrees
711 >>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
712 1.2039930378537762
713
Raymond Hettinger671d7822019-05-01 17:49:12 -0700714 >>> el_niño = NormalDist(4, 2.5)
715 >>> temperature_feb += el_niño # Add in a climate effect
Raymond Hettinger11c79532019-02-23 14:44:07 -0800716 >>> temperature_feb
717 NormalDist(mu=10.0, sigma=6.830080526611674)
718
719 >>> temperature_feb * (9/5) + 32 # Convert to Fahrenheit
720 NormalDist(mu=50.0, sigma=12.294144947901014)
721 >>> temperature_feb.samples(3) # Generate random samples
722 [7.672102882379219, 12.000027119750287, 4.647488369766392]
723
Raymond Hettinger47d99872019-02-21 15:06:29 -0800724
Victor Stinneref9d9b62019-05-22 11:28:22 +0200725sys
726---
727
728Add new :func:`sys.unraisablehook` function which can be overridden to control
729how "unraisable exceptions" are handled. It is called when an exception has
730occurred but there is no way for Python to handle it. For example, when a
731destructor raises an exception or during garbage collection
732(:func:`gc.collect`).
Victor Stinner01ae8972019-06-03 16:28:01 +0200733(Contributed by Victor Stinner in :issue:`36829`.)
Victor Stinneref9d9b62019-05-22 11:28:22 +0200734
735
CAM Gerlache680c3d2019-03-21 09:44:51 -0500736tarfile
737-------
738
739The :mod:`tarfile` module now defaults to the modern pax (POSIX.1-2001)
740format for new archives, instead of the previous GNU-specific one.
741This improves cross-platform portability with a consistent encoding (UTF-8)
742in a standardized and extensible format, and offers several other benefits.
743(Contributed by C.A.M. Gerlach in :issue:`36268`.)
744
745
Victor Stinnercd590a72019-05-28 00:39:52 +0200746threading
747---------
748
749Add a new :func:`threading.excepthook` function which handles uncaught
750:meth:`threading.Thread.run` exception. It can be overridden to control how
751uncaught :meth:`threading.Thread.run` exceptions are handled.
752(Contributed by Victor Stinner in :issue:`1230540`.)
753
754
Tal Einatdfba1f62018-10-24 10:20:05 +0300755tokenize
756--------
757
758The :mod:`tokenize` module now implicitly emits a ``NEWLINE`` token when
759provided with input that does not have a trailing new line. This behavior
760now matches what the C tokenizer does internally.
761(Contributed by Ammar Askar in :issue:`33899`.)
762
Juliette Monselaf5658a2018-10-08 18:29:24 +0200763tkinter
764-------
765
766Added methods :meth:`~tkinter.Spinbox.selection_from`,
767:meth:`~tkinter.Spinbox.selection_present`,
768:meth:`~tkinter.Spinbox.selection_range` and
769:meth:`~tkinter.Spinbox.selection_to`
770in the :class:`tkinter.Spinbox` class.
771(Contributed by Juliette Monsel in :issue:`34829`.)
772
Juliette Monselbf034712018-10-12 18:44:10 +0200773Added method :meth:`~tkinter.Canvas.moveto`
774in the :class:`tkinter.Canvas` class.
775(Contributed by Juliette Monsel in :issue:`23831`.)
776
Zackery Spytz50866e92019-04-05 04:17:13 -0600777The :class:`tkinter.PhotoImage` class now has
778:meth:`~tkinter.PhotoImage.transparency_get` and
779:meth:`~tkinter.PhotoImage.transparency_set` methods. (Contributed by
780Zackery Spytz in :issue:`25451`.)
781
Joannah Nanjekye572168a2019-01-10 19:56:38 +0300782time
783----
784
785Added new clock :data:`~time.CLOCK_UPTIME_RAW` for macOS 10.12.
786(Contributed by Joannah Nanjekye in :issue:`35702`.)
787
Guido van Rossum9b33ce42019-06-11 13:42:35 -0700788
789typing
790------
791
792The :mod:`typing` module incorporates several new features:
793
794* Protocol definitions. See :pep:`544`, :class:`typing.Protocol` and
795 :func:`typing.runtime_checkable`. Simple ABCs like
796 :class:`typing.SupportsInt` are now ``Protocol`` subclasses.
797
798* A dictionary type with per-key types. See :pep:`589` and
799 :class:`typing.TypedDict`.
800
801* Literal types. See :pep:`586` and :class:`typing.Literal`.
802
803* "Final" variables, functions, methods and classes. See :pep:`591`,
804 :class:`typing.Final` and :func:`typing.final`.
805
806* New protocol class :class:`typing.SupportsIndex`.
807
808* New functions :func:`typing.get_origin` and :func:`typing.get_args`.
809
810
Max Bélanger2810dd72018-11-04 15:58:24 -0800811unicodedata
812-----------
813
Benjamin Peterson3aca40d2019-05-08 20:59:35 -0700814* The :mod:`unicodedata` module has been upgraded to use the `Unicode 12.1.0
815 <http://blog.unicode.org/2019/05/unicode-12-1-en.html>`_ release.
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700816
Max Bélanger2810dd72018-11-04 15:58:24 -0800817* New function :func:`~unicodedata.is_normalized` can be used to verify a string
818 is in a specific normal form. (Contributed by Max Belanger and David Euresti in
819 :issue:`32285`).
820
Raymond Hettinger482b6b52019-05-01 17:48:13 -0700821
Lisa Roach0f221d02018-11-08 18:34:33 -0800822unittest
823--------
824
Victor Stinner01ae8972019-06-03 16:28:01 +0200825* Added :class:`AsyncMock` to support an asynchronous version of :class:`Mock`.
Lisa Roach77b3b772019-05-20 09:19:53 -0700826 Appropriate new assert functions for testing have been added as well.
827 (Contributed by Lisa Roach in :issue:`26467`).
828
Lisa Roach0f221d02018-11-08 18:34:33 -0800829* Added :func:`~unittest.addModuleCleanup()` and
830 :meth:`~unittest.TestCase.addClassCleanup()` to unittest to support
831 cleanups for :func:`~unittest.setUpModule()` and
832 :meth:`~unittest.TestCase.setUpClass()`.
833 (Contributed by Lisa Roach in :issue:`24412`.)
834
Petter Strandmark001d63c2019-06-04 21:34:49 +0200835* Several mock assert functions now also print a list of actual calls upon
836 failure. (Contributed by Petter Strandmark in :issue:`35047`.)
837
Brett Cannond64ee1a2018-09-21 15:27:26 -0700838venv
839----
840
841* :mod:`venv` now includes an ``Activate.ps1`` script on all platforms for
842 activating virtual environments under PowerShell Core 6.1.
843 (Contributed by Brett Cannon in :issue:`32718`.)
844
Mark Dickinson7abb6c02019-04-26 15:56:15 +0900845weakref
846-------
847
848* The proxy objects returned by :func:`weakref.proxy` now support the matrix
849 multiplication operators ``@`` and ``@=`` in addition to the other
850 numeric operators. (Contributed by Mark Dickinson in :issue:`36669`.)
851
Christian Heimes17b1d5d2018-09-23 09:50:25 +0200852xml
853---
854
855* As mitigation against DTD and external entity retrieval, the
Andrés Delfinoca682612018-11-07 14:29:14 -0300856 :mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
Christian Heimes17b1d5d2018-09-23 09:50:25 +0200857 external entities by default.
858 (Contributed by Christian Heimes in :issue:`17239`.)
859
Stefan Behnel47541682019-05-03 20:58:16 +0200860* The ``.find*()`` methods in the :mod:`xml.etree.ElementTree` module
861 support wildcard searches like ``{*}tag`` which ignores the namespace
862 and ``{namespace}*`` which returns all tags in the given namespace.
863 (Contributed by Stefan Behnel in :issue:`28238`.)
864
Stefan Behnele1d5dd62019-05-01 22:34:13 +0200865* The :mod:`xml.etree.ElementTree` module provides a new function
866 :func:`–xml.etree.ElementTree.canonicalize()` that implements C14N 2.0.
867 (Contributed by Stefan Behnel in :issue:`13611`.)
868
Stefan Behnele9a465f2019-05-10 10:25:13 +0200869* The target object of :class:`xml.etree.ElementTree.XMLParser` can
870 receive namespace declaration events through the new callback methods
871 ``start_ns()`` and ``end_ns()``. Additionally, the
872 :class:`xml.etree.ElementTree.TreeBuilder` target can be configured
873 to process events about comments and processing instructions to include
874 them in the generated tree.
875 (Contributed by Stefan Behnel in :issue:`36676` and :issue:`36673`.)
Christian Heimes17b1d5d2018-09-23 09:50:25 +0200876
Ned Deily07a18922018-01-31 18:12:38 -0500877Optimizations
878=============
879
Victor Stinner9daecf32019-01-16 00:02:35 +0100880* The :mod:`subprocess` module can now use the :func:`os.posix_spawn` function
881 in some cases for better performance. Currently, it is only used on macOS
882 and Linux (using glibc 2.24 or newer) if all these conditions are met:
883
884 * *close_fds* is false;
Victor Stinnerf6243ac2019-01-23 19:00:39 +0100885 * *preexec_fn*, *pass_fds*, *cwd* and *start_new_session* parameters
886 are not set;
Victor Stinner8c349562019-01-16 23:38:06 +0100887 * the *executable* path contains a directory.
Victor Stinner9daecf32019-01-16 00:02:35 +0100888
Victor Stinner01ae8972019-06-03 16:28:01 +0200889 (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
890
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200891* :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
892 :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
Giampaolo Rodola413d9552019-05-30 14:05:41 +0800893 "fast-copy" syscalls on Linux and macOS in order to copy the file
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -0700894 more efficiently.
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200895 "fast-copy" means that the copying operation occurs within the kernel,
896 avoiding the use of userspace buffers in Python as in
897 "``outfd.write(infd.read())``".
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -0700898 On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB
899 instead of 16 KiB) and a :func:`memoryview`-based variant of
900 :func:`shutil.copyfileobj` is used.
901 The speedup for copying a 512 MiB file within the same partition is about
902 +26% on Linux, +50% on macOS and +40% on Windows. Also, much less CPU cycles
903 are consumed.
904 See :ref:`shutil-platform-dependent-efficient-copy-operations` section.
Mariatta16501b72018-12-06 21:59:42 -0800905 (Contributed by Giampaolo Rodola' in :issue:`33671`.)
Giampaolo Rodola4a172cc2018-06-12 23:04:50 +0200906
Giampaolo Rodola19c46a42018-11-12 06:18:15 -0800907* :func:`shutil.copytree` uses :func:`os.scandir` function and all copy
908 functions depending from it use cached :func:`os.stat` values. The speedup
909 for copying a directory with 8000 files is around +9% on Linux, +20% on
910 Windows and +30% on a Windows SMB share. Also the number of :func:`os.stat`
911 syscalls is reduced by 38% making :func:`shutil.copytree` especially faster
912 on network filesystems. (Contributed by Giampaolo Rodola' in :issue:`33695`.)
913
Łukasz Langac51d8c92018-04-03 23:06:53 -0700914* The default protocol in the :mod:`pickle` module is now Protocol 4,
915 first introduced in Python 3.4. It offers better performance and smaller
916 size compared to Protocol 3 available since Python 3.0.
Ned Deily07a18922018-01-31 18:12:38 -0500917
INADA Naokid5c875b2018-07-11 17:42:49 +0900918* Removed one ``Py_ssize_t`` member from ``PyGC_Head``. All GC tracked
919 objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.
920 (Contributed by Inada Naoki in :issue:`33597`)
921
Tal Einat54752532018-09-10 16:11:04 +0300922* :class:`uuid.UUID` now uses ``__slots__`` to reduce its memory footprint.
Tal Einat54752532018-09-10 16:11:04 +0300923
Raymond Hettinger63fa1cf2019-02-16 12:02:22 -0800924* Improved performance of :func:`operator.itemgetter` by 33%. Optimized
925 argument handling and added a fast path for the common case of a single
926 non-negative integer index into a tuple (which is the typical use case in
927 the standard library). (Contributed by Raymond Hettinger in
928 :issue:`35664`.)
929
930* Sped-up field lookups in :func:`collections.namedtuple`. They are now more
931 than two times faster, making them the fastest form of instance variable
932 lookup in Python. (Contributed by Raymond Hettinger, Pablo Galindo, and
Joe Jevnikf36f8922019-02-21 16:00:40 -0500933 Joe Jevnik, Serhiy Storchaka in :issue:`32492`.)
Raymond Hettinger63fa1cf2019-02-16 12:02:22 -0800934
Pablo Galindoc61e2292018-10-28 22:03:18 +0000935* The :class:`list` constructor does not overallocate the internal item buffer
936 if the input iterable has a known length (the input implements ``__len__``).
Raymond Hettingere1823182019-02-16 12:47:48 -0800937 This makes the created list 12% smaller on average. (Contributed by
938 Raymond Hettinger and Pablo Galindo in :issue:`33234`.)
Pablo Galindoc61e2292018-10-28 22:03:18 +0000939
Stefan Behneld8b9e1f2019-02-20 18:29:24 +0100940* Doubled the speed of class variable writes. When a non-dunder attribute
941 was updated, there was an unnecessary call to update slots.
942 (Contributed by Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger,
943 Neil Schemenauer, and Serhiy Storchaka in :issue:`36012`.)
944
Serhiy Storchaka31913912019-03-14 10:32:22 +0200945* Reduced an overhead of converting arguments passed to many builtin functions
946 and methods. This sped up calling some simple builtin functions and
947 methods up to 20--50%. (Contributed by Serhiy Storchaka in :issue:`23867`,
948 :issue:`35582` and :issue:`36127`.)
949
Inada Naoki91234a12019-06-03 21:30:58 +0900950* ``LOAD_GLOBAL`` instruction now uses new "per opcode cache" mechanism.
951 It is about 40% faster now. (Contributed by Yury Selivanov and Inada Naoki in
952 :issue:`26219`.)
953
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300954
Ned Deily07a18922018-01-31 18:12:38 -0500955Build and C API Changes
956=======================
957
Victor Stinnerbf4ac2d2019-01-22 17:39:03 +0100958* The :c:func:`PyByteArray_Init` and :c:func:`PyByteArray_Fini` functions have
959 been removed. They did nothing since Python 2.7.4 and Python 3.2.0, were
960 excluded from the limited API (stable ABI), and were not documented.
961
Serhiy Storchakaceeef102018-06-15 11:09:43 +0300962* The result of :c:func:`PyExceptionClass_Name` is now of type
963 ``const char *`` rather of ``char *``.
964 (Contributed by Serhiy Storchaka in :issue:`33818`.)
Ned Deily07a18922018-01-31 18:12:38 -0500965
Antoine Pitrou961d54c2018-07-16 19:03:03 +0200966* The duality of ``Modules/Setup.dist`` and ``Modules/Setup`` has been
967 removed. Previously, when updating the CPython source tree, one had
968 to manually copy ``Modules/Setup.dist`` (inside the source tree) to
969 ``Modules/Setup`` (inside the build tree) in order to reflect any changes
970 upstream. This was of a small benefit to packagers at the expense of
971 a frequent annoyance to developers following CPython development, as
972 forgetting to copy the file could produce build failures.
973
974 Now the build system always reads from ``Modules/Setup`` inside the source
975 tree. People who want to customize that file are encouraged to maintain
976 their changes in a git fork of CPython or as patch files, as they would do
977 for any other change to the source tree.
978
979 (Contributed by Antoine Pitrou in :issue:`32430`.)
980
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200981* Functions that convert Python number to C integer like
982 :c:func:`PyLong_AsLong` and argument parsing functions like
983 :c:func:`PyArg_ParseTuple` with integer converting format units like ``'i'``
984 will now use the :meth:`~object.__index__` special method instead of
985 :meth:`~object.__int__`, if available. The deprecation warning will be
986 emitted for objects with the ``__int__()`` method but without the
987 ``__index__()`` method (like :class:`~decimal.Decimal` and
988 :class:`~fractions.Fraction`). :c:func:`PyNumber_Check` will now return
989 ``1`` for objects implementing ``__index__()``.
Serhiy Storchakabdbad712019-06-02 00:05:48 +0300990 :c:func:`PyNumber_Long`, :c:func:`PyNumber_Float` and
991 :c:func:`PyFloat_AsDouble` also now use the ``__index__()`` method if
992 available.
993 (Contributed by Serhiy Storchaka in :issue:`36048` and :issue:`20092`.)
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +0200994
Eddie Elizondo364f0b02019-03-27 07:52:18 -0400995* Heap-allocated type objects will now increase their reference count
996 in :c:func:`PyObject_Init` (and its parallel macro ``PyObject_INIT``)
997 instead of in :c:func:`PyType_GenericAlloc`. Types that modify instance
998 allocation or deallocation may need to be adjusted.
999 (Contributed by Eddie Elizondo in :issue:`35810`.)
1000
Ned Deily07a18922018-01-31 18:12:38 -05001001
1002Deprecated
1003==========
1004
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001005* Deprecated methods ``getchildren()`` and ``getiterator()`` in
1006 the :mod:`~xml.etree.ElementTree` module emit now a
1007 :exc:`DeprecationWarning` instead of :exc:`PendingDeprecationWarning`.
1008 They will be removed in Python 3.9.
1009 (Contributed by Serhiy Storchaka in :issue:`29209`.)
Ned Deily07a18922018-01-31 18:12:38 -05001010
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001011* Passing an object that is not an instance of
1012 :class:`concurrent.futures.ThreadPoolExecutor` to
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001013 :meth:`asyncio.loop.set_default_executor()` is
Elvis Pranskevichus22d25082018-07-30 11:42:43 +01001014 deprecated and will be prohibited in Python 3.9.
1015 (Contributed by Elvis Pranskevichus in :issue:`34075`.)
1016
Berker Peksagef8861c2018-08-21 17:58:49 +03001017* The :meth:`__getitem__` methods of :class:`xml.dom.pulldom.DOMEventStream`,
1018 :class:`wsgiref.util.FileWrapper` and :class:`fileinput.FileInput` have been
1019 deprecated.
1020
1021 Implementations of these methods have been ignoring their *index* parameter,
1022 and returning the next item instead.
1023
1024 (Contributed by Berker Peksag in :issue:`9372`.)
1025
Raymond Hettingerf7b57df2019-03-18 09:53:56 -07001026* The :class:`typing.NamedTuple` class has deprecated the ``_field_types``
1027 attribute in favor of the ``__annotations__`` attribute which has the same
1028 information. (Contributed by Raymond Hettinger in :issue:`36320`.)
1029
Serhiy Storchaka3f228112018-09-27 17:42:37 +03001030* :mod:`ast` classes ``Num``, ``Str``, ``Bytes``, ``NameConstant`` and
1031 ``Ellipsis`` are considered deprecated and will be removed in future Python
1032 versions. :class:`~ast.Constant` should be used instead.
1033 (Contributed by Serhiy Storchaka in :issue:`32892`.)
1034
Serhiy Storchakafec35c92018-10-27 08:00:41 +03001035* The following functions and methods are deprecated in the :mod:`gettext`
1036 module: :func:`~gettext.lgettext`, :func:`~gettext.ldgettext`,
1037 :func:`~gettext.lngettext` and :func:`~gettext.ldngettext`.
1038 They return encoded bytes, and it's possible that you will get unexpected
1039 Unicode-related exceptions if there are encoding problems with the
1040 translated strings. It's much better to use alternatives which return
1041 Unicode strings in Python 3. These functions have been broken for a long time.
1042
1043 Function :func:`~gettext.bind_textdomain_codeset`, methods
1044 :meth:`~gettext.NullTranslations.output_charset` and
1045 :meth:`~gettext.NullTranslations.set_output_charset`, and the *codeset*
1046 parameter of functions :func:`~gettext.translation` and
1047 :func:`~gettext.install` are also deprecated, since they are only used for
1048 for the ``l*gettext()`` functions.
1049
1050 (Contributed by Serhiy Storchaka in :issue:`33710`.)
1051
Dong-hee Na89669ff2019-01-17 21:14:45 +09001052* The :meth:`~threading.Thread.isAlive()` method of :class:`threading.Thread` has been deprecated.
1053 (Contributed by Dong-hee Na in :issue:`35283`.)
Ned Deily07a18922018-01-31 18:12:38 -05001054
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001055* Many builtin and extension functions that take integer arguments will
1056 now emit a deprecation warning for :class:`~decimal.Decimal`\ s,
1057 :class:`~fractions.Fraction`\ s and any other objects that can be converted
1058 to integers only with a loss (e.g. that have the :meth:`~object.__int__`
1059 method but do not have the :meth:`~object.__index__` method). In future
1060 version they will be errors.
1061 (Contributed by Serhiy Storchaka in :issue:`36048`.)
1062
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001063* Deprecated passing the following arguments as keyword arguments:
1064
1065 - *func* in :func:`functools.partialmethod`, :func:`weakref.finalize`,
1066 :meth:`profile.Profile.runcall`, :meth:`cProfile.Profile.runcall`,
1067 :meth:`bdb.Bdb.runcall`, :meth:`trace.Trace.runfunc` and
1068 :func:`curses.wrapper`.
Serhiy Storchaka2085bd02019-06-01 11:00:15 +03001069 - *function* in :meth:`unittest.TestCase.addCleanup`.
Serhiy Storchaka42a139e2019-04-01 09:16:35 +03001070 - *fn* in the :meth:`~concurrent.futures.Executor.submit` method of
1071 :class:`concurrent.futures.ThreadPoolExecutor` and
1072 :class:`concurrent.futures.ProcessPoolExecutor`.
1073 - *callback* in :meth:`contextlib.ExitStack.callback`,
1074 :meth:`contextlib.AsyncExitStack.callback` and
1075 :meth:`contextlib.AsyncExitStack.push_async_callback`.
1076 - *c* and *typeid* in the :meth:`~multiprocessing.managers.Server.create`
1077 method of :class:`multiprocessing.managers.Server` and
1078 :class:`multiprocessing.managers.SharedMemoryServer`.
1079 - *obj* in :func:`weakref.finalize`.
1080
1081 In future releases of Python they will be :ref:`positional-only
1082 <positional-only_parameter>`.
1083 (Contributed by Serhiy Storchaka in :issue:`36492`.)
1084
Serhiy Storchaka6a44f6e2019-02-25 17:57:58 +02001085
Victor Stinner73104fa2018-11-29 09:58:20 +01001086API and Feature Removals
1087========================
1088
1089The following features and APIs have been removed from Python 3.8:
1090
Victor Stinnerd7538dd2018-12-14 13:37:26 +01001091* The :mod:`macpath` module, deprecated in Python 3.7, has been removed.
1092 (Contributed by Victor Stinner in :issue:`35471`.)
1093
Victor Stinner73104fa2018-11-29 09:58:20 +01001094* The function :func:`platform.popen` has been removed, it was deprecated since
1095 Python 3.3: use :func:`os.popen` instead.
Victor Stinner01ae8972019-06-03 16:28:01 +02001096 (Contributed by Victor Stinner in :issue:`35345`.)
Ned Deily07a18922018-01-31 18:12:38 -05001097
Matthias Bussonnierb6a09ae2019-05-13 12:23:07 -07001098* The function :func:`time.clock` has been removed, it was deprecated since Python
1099 3.3: use :func:`time.perf_counter` or :func:`time.process_time` instead, depending
1100 on your requirements, to have a well defined behavior.
Victor Stinner01ae8972019-06-03 16:28:01 +02001101 (Contributed by Matthias Bussonnier in :issue:`36895`.)
Matthias Bussonnierb6a09ae2019-05-13 12:23:07 -07001102
Brett Cannona8c34242018-04-20 14:15:40 -07001103* The ``pyvenv`` script has been removed in favor of ``python3.8 -m venv``
1104 to help eliminate confusion as to what Python interpreter the ``pyvenv``
1105 script is tied to. (Contributed by Brett Cannon in :issue:`25427`.)
Ned Deily07a18922018-01-31 18:12:38 -05001106
INADA Naoki698865d2018-06-19 17:28:50 +09001107* ``parse_qs``, ``parse_qsl``, and ``escape`` are removed from :mod:`cgi`
1108 module. They are deprecated from Python 3.2 or older.
1109
INADA Naoki461a1c42018-06-28 17:10:36 +09001110* ``filemode`` function is removed from :mod:`tarfile` module.
1111 It is not documented and deprecated since Python 3.3.
INADA Naoki698865d2018-06-19 17:28:50 +09001112
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001113* The :class:`~xml.etree.ElementTree.XMLParser` constructor no longer accepts
1114 the *html* argument. It never had effect and was deprecated in Python 3.4.
1115 All other parameters are now :ref:`keyword-only <keyword-only_parameter>`.
1116 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1117
1118* Removed the ``doctype()`` method of :class:`~xml.etree.ElementTree.XMLParser`.
1119 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1120
Inada Naoki6a16b182019-03-18 15:44:11 +09001121* "unicode_internal" codec is removed.
1122 (Contributed by Inada Naoki in :issue:`36297`.)
1123
Aviv Palivodae6576242019-05-09 21:05:45 +03001124* The ``Cache`` and ``Statement`` objects of the :mod:`sqlite3` module are not
1125 exposed to the user.
1126 (Contributed by Aviv Palivoda in :issue:`30262`.)
1127
Matthias Bussonnier1a3faf92019-05-20 13:44:11 -07001128* The ``bufsize`` keyword argument of :func:`fileinput.input` and
1129 :func:`fileinput.FileInput` which was ignored and deprecated since Python 3.6
1130 has been removed. :issue:`36952` (Contributed by Matthias Bussonnier)
1131
Matthias Bussonnier382034b2019-05-28 10:30:35 -07001132* The functions :func:`sys.set_coroutine_wrapper` and
1133 :func:`sys.get_coroutine_wrapper` deprecated in Python 3.7 have been removed;
1134 :issue:`36933` (Contributed by Matthias Bussonnier)
Matthias Bussonnier3880f262019-05-28 00:10:59 -07001135
Ned Deily07a18922018-01-31 18:12:38 -05001136
1137Porting to Python 3.8
1138=====================
1139
1140This section lists previously described changes and other bugfixes
1141that may require changes to your code.
1142
1143
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001144Changes in Python behavior
1145--------------------------
1146
1147* Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
1148 in comprehensions and generator expressions (aside from the iterable expression
Serhiy Storchaka2b57c432018-12-19 08:09:46 +02001149 in the leftmost :keyword:`!for` clause).
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001150 (Contributed by Serhiy Storchaka in :issue:`10544`.)
1151
Serhiy Storchaka3bcbedc2019-01-18 07:47:48 +02001152* The compiler now produces a :exc:`SyntaxWarning` when identity checks
1153 (``is`` and ``is not``) are used with certain types of literals
1154 (e.g. strings, ints). These can often work by accident in CPython,
1155 but are not guaranteed by the language spec. The warning advises users
1156 to use equality tests (``==`` and ``!=``) instead.
1157 (Contributed by Serhiy Storchaka in :issue:`34850`.)
1158
Serhiy Storchaka7a0630c2019-04-08 14:34:04 +03001159* The CPython interpreter can swallow exceptions in some circumstances.
1160 In Python 3.8 this happens in less cases. In particular, exceptions
1161 raised when getting the attribute from the type dictionary are no longer
1162 ignored. (Contributed by Serhiy Storchaka in :issue:`35459`.)
1163
Serhiy Storchaka96aeaec2019-05-06 22:29:40 +03001164* Removed ``__str__`` implementations from builtin types :class:`bool`,
1165 :class:`int`, :class:`float`, :class:`complex` and few classes from
1166 the standard library. They now inherit ``__str__()`` from :class:`object`.
1167 As result, defining the ``__repr__()`` method in the subclass of these
1168 classes will affect they string representation.
1169 (Contributed by Serhiy Storchaka in :issue:`36793`.)
1170
Michael Felt9d949f72019-04-12 16:15:32 +02001171* On AIX, :attr:`sys.platform` doesn't contain the major version anymore.
1172 It is always ``'aix'``, instead of ``'aix3'`` .. ``'aix7'``. Since
1173 older Python versions include the version number, it is recommended to
1174 always use the ``sys.platform.startswith('aix')``.
1175 (Contributed by M. Felt in :issue:`36588`.)
Serhiy Storchaka07ca9af2018-02-04 10:53:48 +02001176
Joannah Nanjekyef781d202019-04-29 04:38:45 -04001177* :c:func:`PyEval_AcquireLock` and :c:func:`PyEval_AcquireThread` now
1178 terminate the current thread if called while the interpreter is
1179 finalizing, making them consistent with :c:func:`PyEval_RestoreThread`,
1180 :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`. If this
1181 behaviour is not desired, guard the call by checking :c:func:`_Py_IsFinalizing`
1182 or :c:func:`sys.is_finalizing`.
1183
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001184Changes in the Python API
1185-------------------------
1186
Victor Stinnerd7befad2019-04-25 14:30:16 +02001187* :class:`subprocess.Popen` can now use :func:`os.posix_spawn` in some cases
1188 for better performance. On Windows Subsystem for Linux and QEMU User
1189 Emulation, Popen constructor using :func:`os.posix_spawn` no longer raise an
1190 exception on errors like missing program, but the child process fails with a
1191 non-zero :attr:`~Popen.returncode`.
Victor Stinner01ae8972019-06-03 16:28:01 +02001192 (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
Victor Stinnerd7befad2019-04-25 14:30:16 +02001193
Victor Stinner74125a62019-04-15 18:23:20 +02001194* The :meth:`imap.IMAP4.logout` method no longer ignores silently arbitrary
1195 exceptions.
1196
Victor Stinner73104fa2018-11-29 09:58:20 +01001197* The function :func:`platform.popen` has been removed, it was deprecated since
1198 Python 3.3: use :func:`os.popen` instead.
Victor Stinner01ae8972019-06-03 16:28:01 +02001199 (Contributed by Victor Stinner in :issue:`35345`.)
Victor Stinner73104fa2018-11-29 09:58:20 +01001200
Raymond Hettingerfc06a192019-03-12 00:43:27 -07001201* The :func:`statistics.mode` function no longer raises an exception
1202 when given multimodal data. Instead, it returns the first mode
1203 encountered in the input data. (Contributed by Raymond Hettinger
1204 in :issue:`35892`.)
1205
Serhiy Storchaka97f1ca12018-02-01 18:49:21 +02001206* The :meth:`~tkinter.ttk.Treeview.selection` method of the
1207 :class:`tkinter.ttk.Treeview` class no longer takes arguments. Using it with
1208 arguments for changing the selection was deprecated in Python 3.6. Use
1209 specialized methods like :meth:`~tkinter.ttk.Treeview.selection_set` for
1210 changing the selection. (Contributed by Serhiy Storchaka in :issue:`31508`.)
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +02001211
Diego Rojas06e1e682019-03-16 18:44:56 -05001212* The :meth:`writexml`, :meth:`toxml` and :meth:`toprettyxml` methods of the
1213 :mod:`xml.dom.minidom` module, and :mod:`xml.etree` now preserve the attribute
1214 order specified by the user.
1215 (Contributed by Diego Rojas and Raymond Hettinger in :issue:`34160`.)
1216
Serhiy Storchaka6c85efa52018-02-05 22:47:31 +02001217* A :mod:`dbm.dumb` database opened with flags ``'r'`` is now read-only.
1218 :func:`dbm.dumb.open` with flags ``'r'`` and ``'w'`` no longer creates
1219 a database if it does not exist.
1220 (Contributed by Serhiy Storchaka in :issue:`32749`.)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001221
Serhiy Storchaka02ec92f2018-07-24 12:03:34 +03001222* The ``doctype()`` method defined in a subclass of
1223 :class:`~xml.etree.ElementTree.XMLParser` will no longer be called and will
1224 cause emitting a :exc:`RuntimeWarning` instead of a :exc:`DeprecationWarning`.
1225 Define the :meth:`doctype() <xml.etree.ElementTree.TreeBuilder.doctype>`
1226 method on a target for handling an XML doctype declaration.
1227 (Contributed by Serhiy Storchaka in :issue:`29209`.)
1228
Serhiy Storchakaf5e7b192018-05-20 08:48:12 +03001229* A :exc:`RuntimeError` is now raised when the custom metaclass doesn't
1230 provide the ``__classcell__`` entry in the namespace passed to
1231 ``type.__new__``. A :exc:`DeprecationWarning` was emitted in Python
1232 3.6--3.7. (Contributed by Serhiy Storchaka in :issue:`23722`.)
1233
Scott Sandersoncebe80b2018-06-07 05:46:42 -04001234* The :class:`cProfile.Profile` class can now be used as a context
1235 manager. (Contributed by Scott Sanderson in :issue:`29235`.)
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001236
Giampaolo Rodolac7f02a92018-06-19 08:27:29 -07001237* :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
1238 :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
1239 "fast-copy" syscalls (see
1240 :ref:`shutil-platform-dependent-efficient-copy-operations` section).
1241
1242* :func:`shutil.copyfile` default buffer size on Windows was changed from
1243 16 KiB to 1 MiB.
1244
INADA Naokid5c875b2018-07-11 17:42:49 +09001245* ``PyGC_Head`` struct is changed completely. All code touched the
1246 struct member should be rewritten. (See :issue:`33597`)
1247
Eric Snowbe3b2952019-02-23 11:35:52 -07001248* The ``PyInterpreterState`` struct has been moved into the "internal"
1249 header files (specifically Include/internal/pycore_pystate.h). An
1250 opaque ``PyInterpreterState`` is still available as part of the public
1251 API (and stable ABI). The docs indicate that none of the struct's
1252 fields are public, so we hope no one has been using them. However,
1253 if you do rely on one or more of those private fields and have no
1254 alternative then please open a BPO issue. We'll work on helping
1255 you adjust (possibly including adding accessor functions to the
1256 public API). (See :issue:`35886`.)
1257
Alex Grönholmcca4eec2018-08-09 00:06:47 +03001258* Asyncio tasks can now be named, either by passing the ``name`` keyword
1259 argument to :func:`asyncio.create_task` or
Yury Selivanov7c7605f2018-09-11 09:54:40 -07001260 the :meth:`~asyncio.loop.create_task` event loop method, or by
Alex Grönholmcca4eec2018-08-09 00:06:47 +03001261 calling the :meth:`~asyncio.Task.set_name` method on the task object. The
1262 task name is visible in the ``repr()`` output of :class:`asyncio.Task` and
1263 can also be retrieved using the :meth:`~asyncio.Task.get_name` method.
1264
Berker Peksage7d4b2f2018-08-22 21:21:05 +03001265* The :meth:`mmap.flush() <mmap.mmap.flush>` method now returns ``None`` on
1266 success and raises an exception on error under all platforms. Previously,
1267 its behavior was platform-depended: a nonzero value was returned on success;
1268 zero was returned on error under Windows. A zero value was returned on
1269 success; an exception was raised on error under Unix.
1270 (Contributed by Berker Peksag in :issue:`2122`.)
1271
Andrés Delfinoca682612018-11-07 14:29:14 -03001272* :mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
Christian Heimes17b1d5d2018-09-23 09:50:25 +02001273 external entities by default.
1274 (Contributed by Christian Heimes in :issue:`17239`.)
INADA Naokid5c875b2018-07-11 17:42:49 +09001275
Xiang Zhang4fb0b8b2018-12-12 20:46:55 +08001276* Deleting a key from a read-only :mod:`dbm` database (:mod:`dbm.dumb`,
1277 :mod:`dbm.gnu` or :mod:`dbm.ndbm`) raises :attr:`error` (:exc:`dbm.dumb.error`,
1278 :exc:`dbm.gnu.error` or :exc:`dbm.ndbm.error`) instead of :exc:`KeyError`.
1279 (Contributed by Xiang Zhang in :issue:`33106`.)
1280
Steve Dower8ef864d2019-03-12 15:15:26 -07001281* :func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
1282 environment variable and does not use :envvar:`HOME`, which is not normally
1283 set for regular user accounts.
1284
Steve Dower2438cdf2019-03-29 16:37:16 -07001285.. _bpo-36085-whatsnew:
1286
1287* DLL dependencies for extension modules and DLLs loaded with :mod:`ctypes` on
1288 Windows are now resolved more securely. Only the system paths, the directory
1289 containing the DLL or PYD file, and directories added with
1290 :func:`~os.add_dll_directory` are searched for load-time dependencies.
1291 Specifically, :envvar:`PATH` and the current working directory are no longer
1292 used, and modifications to these will no longer have any effect on normal DLL
1293 resolution. If your application relies on these mechanisms, you should check
1294 for :func:`~os.add_dll_directory` and if it exists, use it to add your DLLs
Steve Dower79da3882019-03-30 20:58:17 -07001295 directory while loading your library. Note that Windows 7 users will need to
1296 ensure that Windows Update KB2533625 has been installed (this is also verified
1297 by the installer).
Steve Dower2438cdf2019-03-29 16:37:16 -07001298 (See :issue:`36085`.)
1299
Pablo Galindof2cf1e32019-04-13 17:05:14 +01001300* The header files and functions related to pgen have been removed after its
1301 replacement by a pure Python implementation. (Contributed by Pablo Galindo
1302 in :issue:`36623`.)
1303
Pablo Galindo5d23e282019-05-12 22:45:52 +01001304* :class:`types.CodeType` has a new parameter in the second position of the
1305 constructor (*posonlyargcount*) to support positional-only arguments defined
Pablo Galindocd74e662019-06-01 18:08:04 +01001306 in :pep:`570`. The first argument (*argcount*) now represents the total
1307 number of positional arguments (including positional-only arguments). A new
1308 ``replace()`` method of :class:`types.CodeType` can be used to make the code
1309 future-proof.
Pablo Galindo5d23e282019-05-12 22:45:52 +01001310
Xiang Zhang4fb0b8b2018-12-12 20:46:55 +08001311
Inada Naokid3c72a22019-03-23 21:04:40 +09001312Changes in the C API
1313--------------------
1314
Victor Stinnerd5d9e812019-05-13 12:35:37 +02001315* The :c:func:`PyEval_ReInitThreads` function has been removed from the C API.
1316 It should not be called explicitly: use :c:func:`PyOS_AfterFork_Child`
1317 instead.
1318 (Contributed by Victor Stinner in :issue:`36728`.)
1319
E. M. Brayc994c8f2019-05-24 17:33:47 +02001320* On Unix, C extensions are no longer linked to libpython except on Android
1321 and Cygwin. When Python is embedded, ``libpython`` must not be loaded with
xdegaye254b3092019-04-29 09:27:40 +02001322 ``RTLD_LOCAL``, but ``RTLD_GLOBAL`` instead. Previously, using
E. M. Brayc994c8f2019-05-24 17:33:47 +02001323 ``RTLD_LOCAL``, it was already not possible to load C extensions which
1324 were not linked to ``libpython``, like C extensions of the standard
1325 library built by the ``*shared*`` section of ``Modules/Setup``.
Victor Stinner01ae8972019-06-03 16:28:01 +02001326 (Contributed by Victor Stinner in :issue:`21536`.)
Victor Stinner8c3ecc62019-04-25 20:13:10 +02001327
Inada Naokid3c72a22019-03-23 21:04:40 +09001328* Use of ``#`` variants of formats in parsing or building value (e.g.
1329 :c:func:`PyArg_ParseTuple`, :c:func:`Py_BuildValue`, :c:func:`PyObject_CallFunction`,
1330 etc.) without ``PY_SSIZE_T_CLEAN`` defined raises ``DeprecationWarning`` now.
1331 It will be removed in 3.10 or 4.0. Read :ref:`arg-parsing` for detail.
1332 (Contributed by Inada Naoki in :issue:`36381`.)
1333
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001334* Instances of heap-allocated types (such as those created with
1335 :c:func:`PyType_FromSpec`) hold a reference to their type object.
1336 Increasing the reference count of these type objects has been moved from
1337 :c:func:`PyType_GenericAlloc` to the more low-level functions,
1338 :c:func:`PyObject_Init` and :c:func:`PyObject_INIT`.
1339 This makes types created through :c:func:`PyType_FromSpec` behave like
1340 other classes in managed code.
1341
1342 Statically allocated types are not affected.
1343
1344 For the vast majority of cases, there should be no side effect.
1345 However, types that manually increase the reference count after allocating
1346 an instance (perhaps to work around the bug) may now become immortal.
1347 To avoid this, these classes need to call Py_DECREF on the type object
1348 during instance deallocation.
1349
1350 To correctly port these types into 3.8, please apply the following
1351 changes:
1352
1353 * Remove :c:macro:`Py_INCREF` on the type object after allocating an
1354 instance - if any.
1355 This may happen after calling :c:func:`PyObject_New`,
1356 :c:func:`PyObject_NewVar`, :c:func:`PyObject_GC_New`,
1357 :c:func:`PyObject_GC_NewVar`, or any other custom allocator that uses
1358 :c:func:`PyObject_Init` or :c:func:`PyObject_INIT`.
1359
1360 Example::
1361
1362 static foo_struct *
1363 foo_new(PyObject *type) {
1364 foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
1365 if (foo == NULL)
1366 return NULL;
1367 #if PY_VERSION_HEX < 0x03080000
1368 // Workaround for Python issue 35810; no longer necessary in Python 3.8
1369 PY_INCREF(type)
1370 #endif
1371 return foo;
1372 }
1373
1374 * Ensure that all custom ``tp_dealloc`` functions of heap-allocated types
1375 decrease the type's reference count.
1376
1377 Example::
1378
1379 static void
1380 foo_dealloc(foo_struct *instance) {
1381 PyObject *type = Py_TYPE(instance);
1382 PyObject_GC_Del(instance);
1383 #if PY_VERSION_HEX >= 0x03080000
1384 // This was not needed before Python 3.8 (Python issue 35810)
1385 Py_DECREF(type);
1386 #endif
1387 }
1388
1389 (Contributed by Eddie Elizondo in :issue:`35810`.)
1390
Zackery Spytz3c8724f2019-05-28 09:16:33 -06001391* The :c:macro:`Py_DEPRECATED()` macro has been implemented for MSVC.
1392 The macro now must be placed before the symbol name.
1393
1394 Example::
1395
1396 Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
1397
1398 (Contributed by Zackery Spytz in :issue:`33407`.)
1399
Antoine Pitrouada319b2019-05-29 22:12:38 +02001400* The interpreter does not pretend to support binary compatibility of
Xtreak0d702272019-06-03 04:42:33 +05301401 extension types across feature releases, anymore. A :c:type:`PyTypeObject`
Antoine Pitrouada319b2019-05-29 22:12:38 +02001402 exported by a third-party extension module is supposed to have all the
1403 slots expected in the current Python version, including
1404 :c:member:`~PyTypeObject.tp_finalize` (:const:`Py_TPFLAGS_HAVE_FINALIZE`
1405 is not checked anymore before reading :c:member:`~PyTypeObject.tp_finalize`).
1406
1407 (Contributed by Antoine Pitrou in :issue:`32388`.)
1408
Pablo Galindo545a3b82019-05-31 19:33:41 +01001409* The :c:func:`PyCode_New` has a new parameter in the second position (*posonlyargcount*)
1410 to support :pep:`570`, indicating the number of positional-only arguments.
1411
Eddie Elizondo364f0b02019-03-27 07:52:18 -04001412
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001413CPython bytecode changes
1414------------------------
1415
1416* The interpreter loop has been simplified by moving the logic of unrolling
1417 the stack of blocks into the compiler. The compiler emits now explicit
Serhiy Storchaka3f819ca2018-10-31 02:26:06 +02001418 instructions for adjusting the stack of values and calling the
1419 cleaning-up code for :keyword:`break`, :keyword:`continue` and
1420 :keyword:`return`.
Serhiy Storchaka520b7ae2018-02-22 23:33:30 +02001421
1422 Removed opcodes :opcode:`BREAK_LOOP`, :opcode:`CONTINUE_LOOP`,
1423 :opcode:`SETUP_LOOP` and :opcode:`SETUP_EXCEPT`. Added new opcodes
1424 :opcode:`ROT_FOUR`, :opcode:`BEGIN_FINALLY`, :opcode:`CALL_FINALLY` and
1425 :opcode:`POP_FINALLY`. Changed the behavior of :opcode:`END_FINALLY`
1426 and :opcode:`WITH_CLEANUP_START`.
1427
1428 (Contributed by Mark Shannon, Antoine Pitrou and Serhiy Storchaka in
1429 :issue:`17611`.)
Serhiy Storchaka702f8f32018-03-23 14:34:35 +02001430
1431* Added new opcode :opcode:`END_ASYNC_FOR` for handling exceptions raised
1432 when awaiting a next item in an :keyword:`async for` loop.
1433 (Contributed by Serhiy Storchaka in :issue:`33041`.)
Raymond Hettingerf75d59e2019-02-02 22:54:56 -08001434
1435
1436Demos and Tools
1437---------------
1438
1439* Added a benchmark script for timing various ways to access variables:
1440 ``Tools/scripts/var_access_benchmark.py``.
1441 (Contributed by Raymond Hettinger in :issue:`35884`.)