]> granicus.if.org Git - python/blob - Doc/whatsnew/3.8.rst
Announce the change in the CancelledError inheritance (GH-16730)
[python] / Doc / whatsnew / 3.8.rst
1 ****************************
2   What's New In Python 3.8
3 ****************************
4
5 .. 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 Git log
43    when researching a change.
44
45 :Editor: Raymond Hettinger
46
47 This article explains the new features in Python 3.8, compared to 3.7.
48 For full details, see the :ref:`changelog <changelog>`.
49
50 Prerelease users should be aware that this document is currently in
51 draft form. It will be updated as Python 3.8 moves towards release, so
52 it's worth checking back even after reading earlier versions. Some
53 notable items not yet covered are:
54
55 * :pep:`578` - Runtime audit hooks for potentially sensitive operations
56 * ``python -m asyncio`` runs a natively async REPL
57
58 .. testsetup::
59
60    from datetime import date
61    from math import cos, radians
62    from unicodedata import normalize
63    import re
64    import math
65
66
67 Summary -- Release highlights
68 =============================
69
70 .. This section singles out the most important changes in Python 3.8.
71    Brevity is key.
72
73
74 .. PEP-sized items next.
75
76
77
78 New Features
79 ============
80
81 Assignment expressions
82 ----------------------
83
84 There is new syntax ``:=`` that assigns values to variables as part of a larger
85 expression. It is affectionately known as "walrus operator" due to
86 its resemblance to `the eyes and tusks of a walrus
87 <https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg>`_.
88
89 In this example, the assignment expression helps avoid calling
90 :func:`len` twice::
91
92   if (n := len(a)) > 10:
93       print(f"List is too long ({n} elements, expected <= 10)")
94
95 A similar benefit arises during regular expression matching where
96 match objects are needed twice, once to test whether a match
97 occurred and another to extract a subgroup::
98
99   discount = 0.0
100   if (mo := re.search(r'(\d+)% discount', advertisement)):
101       discount = float(mo.group(1)) / 100.0
102
103 The operator is also useful with while-loops that compute
104 a value to test loop termination and then need that same
105 value again in the body of the loop::
106
107   # Loop over fixed length blocks
108   while (block := f.read(256)) != '':
109       process(block)
110
111 Another motivating use case arises in list comprehensions where
112 a value computed in a filtering condition is also needed in
113 the expression body::
114
115    [clean_name.title() for name in names
116     if (clean_name := normalize('NFC', name)) in allowed_names]
117
118 Try to limit use of the walrus operator to clean cases that reduce
119 complexity and improve readability.
120
121 See :pep:`572` for a full description.
122
123 (Contributed by Emily Morehouse in :issue:`35224`.)
124
125
126 Positional-only parameters
127 --------------------------
128
129 There is a new function parameter syntax ``/`` to indicate that some
130 function parameters must be specified positionally and cannot be used as
131 keyword arguments.  This is the same notation shown by ``help()`` for C
132 functions annotated with Larry Hastings' `Argument Clinic
133 <https://docs.python.org/3/howto/clinic.html>`_ tool.
134
135 In the following example, parameters *a* and *b* are positional-only,
136 while *c* or *d* can be positional or keyword, and *e* or *f* are
137 required to be keywords::
138
139   def f(a, b, /, c, d, *, e, f):
140       print(a, b, c, d, e, f)
141
142 The following is a valid call::
143
144   f(10, 20, 30, d=40, e=50, f=60)
145
146 However, these are invalid calls::
147
148   f(10, b=20, c=30, d=40, e=50, f=60)   # b cannot be a keyword argument
149   f(10, 20, 30, 40, 50, f=60)           # e must be a keyword argument
150
151 One use case for this notation is that it allows pure Python functions
152 to fully emulate behaviors of existing C coded functions.  For example,
153 the built-in :func:`pow` function does not accept keyword arguments::
154
155   def pow(x, y, z=None, /):
156       "Emulate the built in pow() function"
157       r = x ** y
158       return r if z is None else r%z
159
160 Another use case is to preclude keyword arguments when the parameter
161 name is not helpful.  For example, the builtin :func:`len` function has
162 the signature ``len(obj, /)``.  This precludes awkward calls such as::
163
164   len(obj='hello')  # The "obj" keyword argument impairs readability
165
166 A further benefit of marking a parameter as positional-only is that it
167 allows the parameter name to be changed in the future without risk of
168 breaking client code.  For example, in the :mod:`statistics` module, the
169 parameter name *dist* may be changed in the future.  This was made
170 possible with the following function specification::
171
172   def quantiles(dist, /, *, n=4, method='exclusive')
173       ...
174
175 Since the parameters to the left of ``/`` are not exposed as possible
176 keywords, the parameters names remain available for use in ``**kwargs``::
177
178   >>> def f(a, b, /, **kwargs):
179   ...     print(a, b, kwargs)
180   ...
181   >>> f(10, 20, a=1, b=2, c=3)         # a and b are used in two ways
182   10 20 {'a': 1, 'b': 2, 'c': 3}
183
184 This greatly simplifies the implementation of functions and methods
185 that need to accept arbitrary keyword arguments.  For example, here
186 is an except from code in the :mod:`collections` module::
187
188   class Counter(dict):
189
190       def __init__(self, iterable=None, /, **kwds):
191           # Note "iterable" is a possible keyword argument
192
193 See :pep:`570` for a full description.
194
195 (Contributed by Pablo Galindo in :issue:`36540`.)
196
197 .. TODO: Pablo will sprint on docs at PyCon US 2019.
198
199
200 Parallel filesystem cache for compiled bytecode files
201 -----------------------------------------------------
202
203 The new :envvar:`PYTHONPYCACHEPREFIX` setting (also available as
204 :option:`-X` ``pycache_prefix``) configures the implicit bytecode
205 cache to use a separate parallel filesystem tree, rather than
206 the default ``__pycache__`` subdirectories within each source
207 directory.
208
209 The location of the cache is reported in :data:`sys.pycache_prefix`
210 (:const:`None` indicates the default location in ``__pycache__``
211 subdirectories).
212
213 (Contributed by Carl Meyer in :issue:`33499`.)
214
215 Debug build uses the same ABI as release build
216 -----------------------------------------------
217
218 Python now uses the same ABI whether it built in release or debug mode. On
219 Unix, when Python is built in debug mode, it is now possible to load C
220 extensions built in release mode and C extensions built using the stable ABI.
221
222 Release builds and debug builds are now ABI compatible: defining the
223 ``Py_DEBUG`` macro no longer implies the ``Py_TRACE_REFS`` macro, which
224 introduces the only ABI incompatibility. The ``Py_TRACE_REFS`` macro, which
225 adds the :func:`sys.getobjects` function and the :envvar:`PYTHONDUMPREFS`
226 environment variable, can be set using the new ``./configure --with-trace-refs``
227 build option.
228 (Contributed by Victor Stinner in :issue:`36465`.)
229
230 On Unix, C extensions are no longer linked to libpython except on Android
231 and Cygwin.
232 It is now possible
233 for a statically linked Python to load a C extension built using a shared
234 library Python.
235 (Contributed by Victor Stinner in :issue:`21536`.)
236
237 On Unix, when Python is built in debug mode, import now also looks for C
238 extensions compiled in release mode and for C extensions compiled with the
239 stable ABI.
240 (Contributed by Victor Stinner in :issue:`36722`.)
241
242 To embed Python into an application, a new ``--embed`` option must be passed to
243 ``python3-config --libs --embed`` to get ``-lpython3.8`` (link the application
244 to libpython). To support both 3.8 and older, try ``python3-config --libs
245 --embed`` first and fallback to ``python3-config --libs`` (without ``--embed``)
246 if the previous command fails.
247
248 Add a pkg-config ``python-3.8-embed`` module to embed Python into an
249 application: ``pkg-config python-3.8-embed --libs`` includes ``-lpython3.8``.
250 To support both 3.8 and older, try ``pkg-config python-X.Y-embed --libs`` first
251 and fallback to ``pkg-config python-X.Y --libs`` (without ``--embed``) if the
252 previous command fails (replace ``X.Y`` with the Python version).
253
254 On the other hand, ``pkg-config python3.8 --libs`` no longer contains
255 ``-lpython3.8``. C extensions must not be linked to libpython (except on
256 Android and Cygwin, whose cases are handled by the script);
257 this change is backward incompatible on purpose.
258 (Contributed by Victor Stinner in :issue:`36721`.)
259
260
261 f-strings support ``=`` for self-documenting expressions and debugging
262 ----------------------------------------------------------------------
263
264 Added an ``=`` specifier to :term:`f-string`\s. An f-string such as
265 ``f'{expr=}'`` will expand to the text of the expression, an equal sign,
266 then the representation of the evaluated expression.  For example:
267
268   >>> user = 'eric_idle'
269   >>> member_since = date(1975, 7, 31)
270   >>> f'{user=} {member_since=}'
271   "user='eric_idle' member_since=datetime.date(1975, 7, 31)"
272
273 The usual :ref:`f-string format specifiers <f-strings>` allow more
274 control over how the result of the expression is displayed::
275
276   >>> delta = date.today() - member_since
277   >>> f'{user=!s}  {delta.days=:,d}'
278   'user=eric_idle  delta.days=16,075'
279
280 The ``=`` specifier will display the whole expression so that
281 calculations can be shown::
282
283   >>> print(f'{theta=}  {cos(radians(theta))=:.3f}')
284   theta=30  cos(radians(theta))=0.866
285
286 (Contributed by Eric V. Smith and Larry Hastings in :issue:`36817`.)
287
288 PEP 587: Python Initialization Configuration
289 --------------------------------------------
290
291 The :pep:`587` adds a new C API to configure the Python Initialization
292 providing finer control on the whole configuration and better error reporting.
293
294 New structures:
295
296 * :c:type:`PyConfig`
297 * :c:type:`PyPreConfig`
298 * :c:type:`PyStatus`
299 * :c:type:`PyWideStringList`
300
301 New functions:
302
303 * :c:func:`PyConfig_Clear`
304 * :c:func:`PyConfig_InitIsolatedConfig`
305 * :c:func:`PyConfig_InitPythonConfig`
306 * :c:func:`PyConfig_Read`
307 * :c:func:`PyConfig_SetArgv`
308 * :c:func:`PyConfig_SetBytesArgv`
309 * :c:func:`PyConfig_SetBytesString`
310 * :c:func:`PyConfig_SetString`
311 * :c:func:`PyPreConfig_InitIsolatedConfig`
312 * :c:func:`PyPreConfig_InitPythonConfig`
313 * :c:func:`PyStatus_Error`
314 * :c:func:`PyStatus_Exception`
315 * :c:func:`PyStatus_Exit`
316 * :c:func:`PyStatus_IsError`
317 * :c:func:`PyStatus_IsExit`
318 * :c:func:`PyStatus_NoMemory`
319 * :c:func:`PyStatus_Ok`
320 * :c:func:`PyWideStringList_Append`
321 * :c:func:`PyWideStringList_Insert`
322 * :c:func:`Py_BytesMain`
323 * :c:func:`Py_ExitStatusException`
324 * :c:func:`Py_InitializeFromConfig`
325 * :c:func:`Py_PreInitialize`
326 * :c:func:`Py_PreInitializeFromArgs`
327 * :c:func:`Py_PreInitializeFromBytesArgs`
328 * :c:func:`Py_RunMain`
329
330 This PEP also adds ``_PyRuntimeState.preconfig`` (:c:type:`PyPreConfig` type)
331 and ``PyInterpreterState.config`` (:c:type:`PyConfig` type) fields to these
332 internal structures. ``PyInterpreterState.config`` becomes the new
333 reference configuration, replacing global configuration variables and
334 other private variables.
335
336 See :ref:`Python Initialization Configuration <init-config>` for the
337 documentation.
338
339 See :pep:`587` for a full description.
340
341 (Contributed by Victor Stinner in :issue:`36763`.)
342
343
344 Vectorcall: a fast calling protocol for CPython
345 -----------------------------------------------
346
347 The "vectorcall" protocol is added to the Python/C API.
348 It is meant to formalize existing optimizations which were already done
349 for various classes.
350 Any extension type implementing a callable can use this protocol.
351
352 This is currently provisional,
353 the aim is to make it fully public in Python 3.9.
354
355 See :pep:`590` for a full description.
356
357 (Contributed by Jeroen Demeyer and Mark Shannon in :issue:`36974`.)
358
359
360 Pickle protocol 5 with out-of-band data buffers
361 -----------------------------------------------
362
363 When :mod:`pickle` is used to transfer large data between Python processes
364 in order to take advantage of multi-core or multi-machine processing,
365 it is important to optimize the transfer by reducing memory copies, and
366 possibly by applying custom techniques such as data-dependent compression.
367
368 The :mod:`pickle` protocol 5 introduces support for out-of-band buffers
369 where :pep:`3118`-compatible data can be transmitted separately from the
370 main pickle stream, at the discretion of the communication layer.
371
372 See :pep:`574` for a full description.
373
374 (Contributed by Antoine Pitrou in :issue:`36785`.)
375
376
377 Other Language Changes
378 ======================
379
380 * A :keyword:`continue` statement was illegal in the :keyword:`finally` clause
381   due to a problem with the implementation.  In Python 3.8 this restriction
382   was lifted.
383   (Contributed by Serhiy Storchaka in :issue:`32489`.)
384
385 * The :class:`bool`, :class:`int`, and :class:`fractions.Fraction` types
386   now have an :meth:`~int.as_integer_ratio` method like that found in
387   :class:`float` and :class:`decimal.Decimal`.  This minor API extension
388   makes it possible to write ``numerator, denominator =
389   x.as_integer_ratio()`` and have it work across multiple numeric types.
390   (Contributed by Lisa Roach in :issue:`33073` and Raymond Hettinger in
391   :issue:`37819`.)
392
393 * Constructors of :class:`int`, :class:`float` and :class:`complex` will now
394   use the :meth:`~object.__index__` special method, if available and the
395   corresponding method :meth:`~object.__int__`, :meth:`~object.__float__`
396   or :meth:`~object.__complex__` is not available.
397   (Contributed by Serhiy Storchaka in :issue:`20092`.)
398
399 * Added support of ``\N{name}`` escapes in :mod:`regular expressions <re>`::
400
401     >>> notice = 'Copyright © 2019'
402     >>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})')
403     >>> int(copyright_year_pattern.search(notice).group(1))
404     2019
405
406   (Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.)
407
408 * Dict and dictviews are now iterable in reversed insertion order using
409   :func:`reversed`. (Contributed by Rémi Lapeyre in :issue:`33462`.)
410
411 * The syntax allowed for keyword names in function calls was further
412   restricted. In particular, ``f((keyword)=arg)`` is no longer allowed. It was
413   never intended to permit more than a bare name on the left-hand side of a
414   keyword argument assignment term. See :issue:`34641`.
415
416 * Generalized iterable unpacking in :keyword:`yield` and
417   :keyword:`return` statements no longer requires enclosing parentheses.
418   This brings the *yield* and *return* syntax into better agreement with
419   normal assignment syntax::
420
421     >>> def parse(family):
422             lastname, *members = family.split()
423             return lastname.upper(), *members
424
425     >>> parse('simpsons homer marge bart lisa sally')
426     ('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'sally')
427
428
429   (Contributed by David Cuthbert and Jordan Chapman in :issue:`32117`.)
430
431 * When a comma is missed in code such as ``[(10, 20) (30, 40)]``, the
432   compiler displays a :exc:`SyntaxWarning` with a helpful suggestion.
433   This improves on just having a :exc:`TypeError` indicating that the
434   first tuple was not callable.  (Contributed by Serhiy Storchaka in
435   :issue:`15248`.)
436
437 * Arithmetic operations between subclasses of :class:`datetime.date` or
438   :class:`datetime.datetime` and :class:`datetime.timedelta` objects now return
439   an instance of the subclass, rather than the base class. This also affects
440   the return type of operations whose implementation (directly or indirectly)
441   uses :class:`datetime.timedelta` arithmetic, such as
442   :meth:`datetime.datetime.astimezone`.
443   (Contributed by Paul Ganssle in :issue:`32417`.)
444
445 * When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the
446   resulting :exc:`KeyboardInterrupt` exception is not caught, the Python process
447   now exits via a SIGINT signal or with the correct exit code such that the
448   calling process can detect that it died due to a Ctrl-C.  Shells on POSIX
449   and Windows use this to properly terminate scripts in interactive sessions.
450   (Contributed by Google via Gregory P. Smith in :issue:`1054041`.)
451
452 * Some advanced styles of programming require updating the
453   :class:`types.CodeType` object for an existing function.  Since code
454   objects are immutable, a new code object needs to be created, one
455   that is modeled on the existing code object.  With 19 parameters,
456   this was somewhat tedious.  Now, the new ``replace()`` method makes
457   it possible to create a clone with a few altered parameters.
458
459   Here's an example that alters the :func:`statistics.mean` function to
460   prevent the *data* parameter from being used as a keyword argument::
461
462     >>> from statistics import mean
463     >>> mean(data=[10, 20, 90])
464     40
465     >>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
466     >>> mean(data=[10, 20, 90])
467     Traceback (most recent call last):
468       ...
469     TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'
470
471   (Contributed by Victor Stinner in :issue:`37032`.)
472
473 * For integers, the three-argument form of the :func:`pow` function now
474   permits the exponent to be negative in the case where the base is
475   relatively prime to the modulus. It then computes a modular inverse to
476   the base when the exponent is ``-1``, and a suitable power of that
477   inverse for other negative exponents.  For example, to compute the
478   `modular multiplicative inverse
479   <https://en.wikipedia.org/wiki/Modular_multiplicative_inverse>`_ of 38
480   modulo 137, write::
481
482     >>> pow(38, -1, 137)
483     119
484     >>> 119 * 38 % 137
485     1
486
487   Modular inverses arise in the solution of `linear Diophantine
488   equations <https://en.wikipedia.org/wiki/Diophantine_equation>`_.
489   For example, to find integer solutions for ``4258𝑥 + 147𝑦 = 369``,
490   first rewrite as ``4258𝑥 ≡ 369 (mod 147)`` then solve:
491
492     >>> x = 369 * pow(4258, -1, 147) % 147
493     >>> y = (4258 * x - 369) // -147
494     >>> 4258 * x + 147 * y
495     369
496
497   (Contributed by Mark Dickinson in :issue:`36027`.)
498
499 * Dict comprehensions have been synced-up with dict literals so that the
500   key is computed first and the value second::
501
502     >>> # Dict comprehension
503     >>> cast = {input('role? '): input('actor? ') for i in range(2)}
504     role? King Arthur
505     actor? Chapman
506     role? Black Knight
507     actor? Cleese
508
509     >>> # Dict literal
510     >>> cast = {input('role? '): input('actor? ')}
511     role? Sir Robin
512     actor? Eric Idle
513
514   The guaranteed execution order is helpful with assignment expressions
515   because variables assigned in the key expression will be available in
516   the value expression::
517
518     >>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
519     >>> {(n := normalize('NFC', name)).casefold() : n for name in names}
520     {'martin von löwis': 'Martin von Löwis',
521      'łukasz langa': 'Łukasz Langa',
522      'walter dörwald': 'Walter Dörwald'}
523
524
525 New Modules
526 ===========
527
528 * The new :mod:`importlib.metadata` module provides (provisional) support for
529   reading metadata from third-party packages.  For example, it can extract an
530   installed package's version number, list of entry points, and more::
531
532     >>> # Note following example requires that the popular "requests"
533     >>> # package has been installed.
534     >>>
535     >>> from importlib.metadata import version, requires, files
536     >>> version('requests')
537     '2.22.0'
538     >>> list(requires('requests'))
539     ['chardet (<3.1.0,>=3.0.2)']
540     >>> list(files('requests'))[:5]
541     [PackagePath('requests-2.22.0.dist-info/INSTALLER'),
542      PackagePath('requests-2.22.0.dist-info/LICENSE'),
543      PackagePath('requests-2.22.0.dist-info/METADATA'),
544      PackagePath('requests-2.22.0.dist-info/RECORD'),
545      PackagePath('requests-2.22.0.dist-info/WHEEL')]
546
547   (Contributed in :issue:`34632` by Barry Warsaw and Jason R. Coombs.)
548
549
550 Improved Modules
551 ================
552
553
554 ast
555 ---
556
557 AST nodes now have ``end_lineno`` and ``end_col_offset`` attributes,
558 which give the precise location of the end of the node.  (This only
559 applies to nodes that have ``lineno`` and ``col_offset`` attributes.)
560
561 The :func:`ast.parse` function has some new flags:
562
563 * ``type_comments=True`` causes it to return the text of :pep:`484` and
564   :pep:`526` type comments associated with certain AST nodes;
565
566 * ``mode='func_type'`` can be used to parse :pep:`484` "signature type
567   comments" (returned for function definition AST nodes);
568
569 * ``feature_version=(3, N)`` allows specifying an earlier Python 3
570   version.  (For example, ``feature_version=(3, 4)`` will treat
571   ``async`` and ``await`` as non-reserved words.)
572
573 New function :func:`ast.get_source_segment` returns the source code
574 for a specific AST node.
575
576
577 asyncio
578 -------
579
580 On Windows, the default event loop is now :class:`~asyncio.ProactorEventLoop`.
581 (Contributed by Victor Stinner in :issue:`34687`.)
582
583 :class:`~asyncio.ProactorEventLoop` now also supports UDP.
584 (Contributed by Adam Meily and Andrew Svetlov in :issue:`29883`.)
585
586 :class:`~asyncio.ProactorEventLoop` can now be interrupted by
587 :exc:`KeyboardInterrupt` ("CTRL+C").
588 (Contributed by Vladimir Matveev in :issue:`23057`.)
589
590
591 builtins
592 --------
593
594 The :func:`compile` built-in has been improved to accept the
595 ``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` flag. With this new flag passed,
596 :func:`compile` will allow top-level ``await``, ``async for`` and ``async with``
597 constructs that are usually considered invalid syntax. Asynchronous code object
598 marked with the ``CO_COROUTINE`` flag may then be returned.
599
600 (Contributed by Matthias Bussonnier in :issue:`34616`)
601
602 collections
603 -----------
604
605 The :meth:`_asdict()` method for :func:`collections.namedtuple` now returns
606 a :class:`dict` instead of a :class:`collections.OrderedDict`. This works because
607 regular dicts have guaranteed ordering since Python 3.7. If the extra
608 features of :class:`OrderedDict` are required, the suggested remediation is
609 to cast the result to the desired type: ``OrderedDict(nt._asdict())``.
610 (Contributed by Raymond Hettinger in :issue:`35864`.)
611
612
613 ctypes
614 ------
615
616 On Windows, :class:`~ctypes.CDLL` and subclasses now accept a *winmode* parameter
617 to specify flags for the underlying ``LoadLibraryEx`` call. The default flags are
618 set to only load DLL dependencies from trusted locations, including the path
619 where the DLL is stored (if a full or partial path is used to load the initial
620 DLL) and paths added by :func:`~os.add_dll_directory`.
621
622
623 functools
624 ---------
625
626 :func:`functools.lru_cache` can now be used as a straight decorator rather
627 than as a function returning a decorator.  So both of these are now supported::
628
629     @lru_cache
630     def f(x):
631         ...
632
633     @lru_cache(maxsize=256)
634     def f(x):
635         ...
636
637 (Contributed by Raymond Hettinger in :issue:`36772`.)
638
639
640 datetime
641 --------
642
643 Added new alternate constructors :meth:`datetime.date.fromisocalendar` and
644 :meth:`datetime.datetime.fromisocalendar`, which construct :class:`date` and
645 :class:`datetime` objects respectively from ISO year, week number and weekday;
646 these are the inverse of each class's ``isocalendar`` method.
647 (Contributed by Paul Ganssle in :issue:`36004`.)
648
649
650 gettext
651 -------
652
653 Added :func:`~gettext.pgettext` and its variants.
654 (Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in :issue:`2504`.)
655
656
657 idlelib and IDLE
658 ----------------
659
660 Output over N lines (50 by default) is squeezed down to a button.
661 N can be changed in the PyShell section of the General page of the
662 Settings dialog.  Fewer, but possibly extra long, lines can be squeezed by
663 right clicking on the output.  Squeezed output can be expanded in place
664 by double-clicking the button or into the clipboard or a separate window
665 by right-clicking the button.  (Contributed by Tal Einat in :issue:`1529353`.)
666
667 Add "Run Customized" to the Run menu to run a module with customized
668 settings. Any command line arguments entered are added to sys.argv.
669 They also re-appear in the box for the next customized run.  One can also
670 suppress the normal Shell main module restart.  (Contributed by Cheryl
671 Sabella, Terry Jan Reedy, and others in :issue:`5680` and :issue:`37627`.)
672
673 Add optional line numbers for IDLE editor windows. Windows
674 open without line numbers unless set otherwise in the General
675 tab of the configuration dialog.  Line numbers for an existing
676 window are shown and hidden in the Options menu.
677 (Contributed by Tal Einat and Saimadhav Heblikar in :issue:`17535`.)
678
679 The changes above have been backported to 3.7 maintenance releases.
680
681
682 inspect
683 -------
684
685 The :func:`inspect.getdoc` function can now find docstrings for ``__slots__``
686 if that attribute is a :class:`dict` where the values are docstrings.
687 This provides documentation options similar to what we already have
688 for :func:`property`, :func:`classmethod`, and :func:`staticmethod`::
689
690   class AudioClip:
691       __slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
692                    'duration': 'in seconds, rounded up to an integer'}
693       def __init__(self, bit_rate, duration):
694           self.bit_rate = round(bit_rate / 1000.0, 1)
695           self.duration = ceil(duration)
696
697
698 io
699 --
700
701 In development mode (:option:`-X` ``env``) and in debug build, the
702 :class:`io.IOBase` finalizer now logs the exception if the ``close()`` method
703 fails. The exception is ignored silently by default in release build.
704 (Contributed by Victor Stinner in :issue:`18748`.)
705
706
707 gc
708 --
709
710 :func:`~gc.get_objects` can now receive an optional *generation* parameter
711 indicating a generation to get objects from. Contributed in
712 :issue:`36016` by Pablo Galindo.
713
714
715 gzip
716 ----
717
718 Added the *mtime* parameter to :func:`gzip.compress` for reproducible output.
719 (Contributed by Guo Ci Teo in :issue:`34898`.)
720
721 A :exc:`~gzip.BadGzipFile` exception is now raised instead of :exc:`OSError`
722 for certain types of invalid or corrupt gzip files.
723 (Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in
724 :issue:`6584`.)
725
726
727 idlelib and IDLE
728 ----------------
729
730 Add optional line numbers for IDLE editor windows. Windows
731 open without line numbers unless set otherwise in the General
732 tab of the configuration dialog.
733 (Contributed by Tal Einat and Saimadhav Heblikar in :issue:`17535`.)
734
735 Output over N lines (50 by default) is squeezed down to a button.
736 N can be changed in the PyShell section of the General page of the
737 Settings dialog.  Fewer, but possibly extra long, lines can be squeezed by
738 right clicking on the output.  Squeezed output can be expanded in place
739 by double-clicking the button or into the clipboard or a separate window
740 by right-clicking the button.  (Contributed by Tal Einat in :issue:`1529353`.)
741
742 The changes above have been backported to 3.7 maintenance releases.
743
744
745 json.tool
746 ---------
747
748 Add option ``--json-lines`` to parse every input line as separate JSON object.
749 (Contributed by Weipeng Hong in :issue:`31553`.)
750
751
752 math
753 ----
754
755 Added new function :func:`math.dist` for computing Euclidean distance
756 between two points.  (Contributed by Raymond Hettinger in :issue:`33089`.)
757
758 Expanded the :func:`math.hypot` function to handle multiple dimensions.
759 Formerly, it only supported the 2-D case.
760 (Contributed by Raymond Hettinger in :issue:`33089`.)
761
762 Added new function, :func:`math.prod`, as analogous function to :func:`sum`
763 that returns the product of a 'start' value (default: 1) times an iterable of
764 numbers::
765
766     >>> prior = 0.8
767     >>> likelihoods = [0.625, 0.84, 0.30]
768     >>> math.prod(likelihoods, start=prior)
769     0.126
770
771 (Contributed by Pablo Galindo in :issue:`35606`)
772
773 Added new function :func:`math.isqrt` for computing integer square roots.
774 (Contributed by Mark Dickinson in :issue:`36887`.)
775
776 The function :func:`math.factorial` no longer accepts arguments that are not
777 int-like. (Contributed by Pablo Galindo in :issue:`33083`.)
778
779
780 mmap
781 ----
782
783 The :class:`mmap.mmap` class now has an :meth:`~mmap.mmap.madvise` method to
784 access the ``madvise()`` system call.
785 (Contributed by Zackery Spytz in :issue:`32941`.)
786
787
788 multiprocessing
789 ---------------
790
791 Added new :mod:`multiprocessing.shared_memory` module.
792 (Contributed Davin Potts in :issue:`35813`.)
793
794 On macOS, the *spawn* start method is now used by default.
795 (Contributed by Victor Stinner in :issue:`33725`.)
796
797
798 os
799 --
800
801 Added new function :func:`~os.add_dll_directory` on Windows for providing
802 additional search paths for native dependencies when importing extension
803 modules or loading DLLs using :mod:`ctypes`.
804
805 A new :func:`os.memfd_create` function was added to wrap the
806 ``memfd_create()`` syscall.
807 (Contributed by Zackery Spytz and Christian Heimes in :issue:`26836`.)
808
809 On Windows, much of the manual logic for handling reparse points (including
810 symlinks and directory junctions) has been delegated to the operating system.
811 Specifically, :func:`os.stat` will now traverse anything supported by the
812 operating system, while :func:`os.lstat` will only open reparse points that
813 identify as "name surrogates" while others are opened as for :func:`os.stat`.
814 In all cases, :attr:`stat_result.st_mode` will only have ``S_IFLNK`` set for
815 symbolic links and not other kinds of reparse points. To identify other kinds
816 of reparse point, check the new :attr:`stat_result.st_reparse_tag` attribute.
817
818 On Windows, :func:`os.readlink` is now able to read directory junctions. Note
819 that :func:`~os.path.islink` will return ``False`` for directory junctions,
820 and so code that checks ``islink`` first will continue to treat junctions as
821 directories, while code that handles errors from :func:`os.readlink` may now
822 treat junctions as links.
823
824
825 os.path
826 -------
827
828 :mod:`os.path` functions that return a boolean result like
829 :func:`~os.path.exists`, :func:`~os.path.lexists`, :func:`~os.path.isdir`,
830 :func:`~os.path.isfile`, :func:`~os.path.islink`, and :func:`~os.path.ismount`
831 now return ``False`` instead of raising :exc:`ValueError` or its subclasses
832 :exc:`UnicodeEncodeError` and :exc:`UnicodeDecodeError` for paths that contain
833 characters or bytes unrepresentable at the OS level.
834 (Contributed by Serhiy Storchaka in :issue:`33721`.)
835
836 :func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
837 environment variable and does not use :envvar:`HOME`, which is not normally set
838 for regular user accounts.
839
840 :func:`~os.path.isdir` on Windows no longer returns true for a link to a
841 non-existent directory.
842
843 :func:`~os.path.realpath` on Windows now resolves reparse points, including
844 symlinks and directory junctions.
845
846
847 ncurses
848 -------
849
850 Added a new variable holding structured version information for the
851 underlying ncurses library: :data:`~curses.ncurses_version`.
852 (Contributed by Serhiy Storchaka in :issue:`31680`.)
853
854
855 pathlib
856 -------
857
858 :mod:`pathlib.Path` methods that return a boolean result like
859 :meth:`~pathlib.Path.exists()`, :meth:`~pathlib.Path.is_dir()`,
860 :meth:`~pathlib.Path.is_file()`, :meth:`~pathlib.Path.is_mount()`,
861 :meth:`~pathlib.Path.is_symlink()`, :meth:`~pathlib.Path.is_block_device()`,
862 :meth:`~pathlib.Path.is_char_device()`, :meth:`~pathlib.Path.is_fifo()`,
863 :meth:`~pathlib.Path.is_socket()` now return ``False`` instead of raising
864 :exc:`ValueError` or its subclass :exc:`UnicodeEncodeError` for paths that
865 contain characters unrepresentable at the OS level.
866 (Contributed by Serhiy Storchaka in :issue:`33721`.)
867
868 Added :meth:`pathlib.Path.link_to()` which creates a hard link pointing
869 to a path.
870 (Contributed by Joannah Nanjekye in :issue:`26978`)
871
872
873 pickle
874 ------
875
876 Reduction methods can now include a 6th item in the tuple they return. This
877 item should specify a custom state-setting method that's called instead of the
878 regular ``__setstate__`` method.
879 (Contributed by Pierre Glaser and Olivier Grisel in :issue:`35900`)
880
881 :mod:`pickle` extensions subclassing the C-optimized :class:`~pickle.Pickler`
882 can now override the pickling logic of functions and classes by defining the
883 special :meth:`~pickle.Pickler.reducer_override` method.
884 (Contributed by Pierre Glaser and Olivier Grisel in :issue:`35900`)
885
886
887 plistlib
888 --------
889
890 Added new :class:`plistlib.UID` and enabled support for reading and writing
891 NSKeyedArchiver-encoded binary plists.
892 (Contributed by Jon Janzen in :issue:`26707`.)
893
894
895 py_compile
896 ----------
897
898 :func:`py_compile.compile` now supports silent mode.
899 (Contributed by Joannah Nanjekye in :issue:`22640`.)
900
901
902 socket
903 ------
904
905 Added :meth:`~socket.create_server()` and :meth:`~socket.has_dualstack_ipv6()`
906 convenience functions to automate the necessary tasks usually involved when
907 creating a server socket, including accepting both IPv4 and IPv6 connections
908 on the same socket.  (Contributed by Giampaolo Rodola in :issue:`17561`.)
909
910 The :func:`socket.if_nameindex()`, :func:`socket.if_nametoindex()`, and
911 :func:`socket.if_indextoname()` functions have been implemented on Windows.
912 (Contributed by Zackery Spytz in :issue:`37007`.)
913
914 shlex
915 ----------
916
917 The new :func:`shlex.join` function acts as the inverse of :func:`shlex.split`.
918 (Contributed by Bo Bayles in :issue:`32102`.)
919
920 shutil
921 ------
922
923 :func:`shutil.copytree` now accepts a new ``dirs_exist_ok`` keyword argument.
924 (Contributed by Josh Bronson in :issue:`20849`.)
925
926 :func:`shutil.make_archive` now defaults to the modern pax (POSIX.1-2001)
927 format for new archives to improve portability and standards conformance,
928 inherited from the corresponding change to the :mod:`tarfile` module.
929 (Contributed by C.A.M. Gerlach in :issue:`30661`.)
930
931 :func:`shutil.rmtree` on Windows now removes directory junctions without
932 recursively removing their contents first.
933
934
935 ssl
936 ---
937
938 Added :attr:`SSLContext.post_handshake_auth` to enable and
939 :meth:`ssl.SSLSocket.verify_client_post_handshake` to initiate TLS 1.3
940 post-handshake authentication.
941 (Contributed by Christian Heimes in :issue:`34670`.)
942
943
944 statistics
945 ----------
946
947 Added :func:`statistics.fmean` as a faster, floating point variant of
948 :func:`statistics.mean()`.  (Contributed by Raymond Hettinger and
949 Steven D'Aprano in :issue:`35904`.)
950
951 Added :func:`statistics.geometric_mean()`
952 (Contributed by Raymond Hettinger in :issue:`27181`.)
953
954 Added :func:`statistics.multimode` that returns a list of the most
955 common values. (Contributed by Raymond Hettinger in :issue:`35892`.)
956
957 Added :func:`statistics.quantiles` that divides data or a distribution
958 in to equiprobable intervals (e.g. quartiles, deciles, or percentiles).
959 (Contributed by Raymond Hettinger in :issue:`36546`.)
960
961 Added :class:`statistics.NormalDist`, a tool for creating
962 and manipulating normal distributions of a random variable.
963 (Contributed by Raymond Hettinger in :issue:`36018`.)
964
965 ::
966
967     >>> temperature_feb = NormalDist.from_samples([4, 12, -3, 2, 7, 14])
968     >>> temperature_feb.mean
969     6.0
970     >>> temperature_feb.stdev
971     6.356099432828281
972
973     >>> temperature_feb.cdf(3)            # Chance of being under 3 degrees
974     0.3184678262814532
975     >>> # Relative chance of being 7 degrees versus 10 degrees
976     >>> temperature_feb.pdf(7) / temperature_feb.pdf(10)
977     1.2039930378537762
978
979     >>> el_niño = NormalDist(4, 2.5)
980     >>> temperature_feb += el_niño        # Add in a climate effect
981     >>> temperature_feb
982     NormalDist(mu=10.0, sigma=6.830080526611674)
983
984     >>> temperature_feb * (9/5) + 32      # Convert to Fahrenheit
985     NormalDist(mu=50.0, sigma=12.294144947901014)
986     >>> temperature_feb.samples(3)        # Generate random samples
987     [7.672102882379219, 12.000027119750287, 4.647488369766392]
988
989
990 sys
991 ---
992
993 Add new :func:`sys.unraisablehook` function which can be overridden to control
994 how "unraisable exceptions" are handled. It is called when an exception has
995 occurred but there is no way for Python to handle it. For example, when a
996 destructor raises an exception or during garbage collection
997 (:func:`gc.collect`).
998 (Contributed by Victor Stinner in :issue:`36829`.)
999
1000
1001 tarfile
1002 -------
1003
1004 The :mod:`tarfile` module now defaults to the modern pax (POSIX.1-2001)
1005 format for new archives, instead of the previous GNU-specific one.
1006 This improves cross-platform portability with a consistent encoding (UTF-8)
1007 in a standardized and extensible format, and offers several other benefits.
1008 (Contributed by C.A.M. Gerlach in :issue:`36268`.)
1009
1010
1011 threading
1012 ---------
1013
1014 * Add a new :func:`threading.excepthook` function which handles uncaught
1015   :meth:`threading.Thread.run` exception. It can be overridden to control how
1016   uncaught :meth:`threading.Thread.run` exceptions are handled.
1017   (Contributed by Victor Stinner in :issue:`1230540`.)
1018
1019 * Add a new
1020   :func:`threading.get_native_id` function and a :data:`~threading.Thread.native_id`
1021   attribute to the :class:`threading.Thread` class. These return the native
1022   integral Thread ID of the current thread assigned by the kernel.
1023   This feature is only available on certain platforms, see
1024   :func:`get_native_id <threading.get_native_id>` for more information.
1025   (Contributed by Jake Tesler in :issue:`36084`.)
1026
1027
1028 tokenize
1029 --------
1030
1031 The :mod:`tokenize` module now implicitly emits a ``NEWLINE`` token when
1032 provided with input that does not have a trailing new line.  This behavior
1033 now matches what the C tokenizer does internally.
1034 (Contributed by Ammar Askar in :issue:`33899`.)
1035
1036 tkinter
1037 -------
1038
1039 Added methods :meth:`~tkinter.Spinbox.selection_from`,
1040 :meth:`~tkinter.Spinbox.selection_present`,
1041 :meth:`~tkinter.Spinbox.selection_range` and
1042 :meth:`~tkinter.Spinbox.selection_to`
1043 in the :class:`tkinter.Spinbox` class.
1044 (Contributed by Juliette Monsel in :issue:`34829`.)
1045
1046 Added method :meth:`~tkinter.Canvas.moveto`
1047 in the :class:`tkinter.Canvas` class.
1048 (Contributed by Juliette Monsel in :issue:`23831`.)
1049
1050 The :class:`tkinter.PhotoImage` class now has
1051 :meth:`~tkinter.PhotoImage.transparency_get` and
1052 :meth:`~tkinter.PhotoImage.transparency_set` methods.  (Contributed by
1053 Zackery Spytz in :issue:`25451`.)
1054
1055 time
1056 ----
1057
1058 Added new clock :data:`~time.CLOCK_UPTIME_RAW` for macOS 10.12.
1059 (Contributed by Joannah Nanjekye in :issue:`35702`.)
1060
1061
1062 typing
1063 ------
1064
1065 The :mod:`typing` module incorporates several new features:
1066
1067 * Protocol definitions.  See :pep:`544`, :class:`typing.Protocol` and
1068   :func:`typing.runtime_checkable`.  Simple ABCs like
1069   :class:`typing.SupportsInt` are now ``Protocol`` subclasses.
1070
1071 * A dictionary type with per-key types.  See :pep:`589` and
1072   :class:`typing.TypedDict`.
1073
1074 * Literal types.  See :pep:`586` and :class:`typing.Literal`.
1075
1076 * "Final" variables, functions, methods and classes.  See :pep:`591`,
1077   :class:`typing.Final` and :func:`typing.final`.
1078
1079 * New protocol class :class:`typing.SupportsIndex`.
1080
1081 * New functions :func:`typing.get_origin` and :func:`typing.get_args`.
1082
1083
1084 unicodedata
1085 -----------
1086
1087 * The :mod:`unicodedata` module has been upgraded to use the `Unicode 12.1.0
1088   <http://blog.unicode.org/2019/05/unicode-12-1-en.html>`_ release.
1089
1090 * New function :func:`~unicodedata.is_normalized` can be used to verify a string
1091   is in a specific normal form, often much faster than by actually normalizing
1092   the string.  (Contributed by Max Belanger, David Euresti, and Greg Price in
1093   :issue:`32285` and :issue:`37966`).
1094
1095
1096 unittest
1097 --------
1098
1099 * Added :class:`AsyncMock` to support an asynchronous version of :class:`Mock`.
1100   Appropriate new assert functions for testing have been added as well.
1101   (Contributed by Lisa Roach in :issue:`26467`).
1102
1103 * Added :func:`~unittest.addModuleCleanup()` and
1104   :meth:`~unittest.TestCase.addClassCleanup()` to unittest to support
1105   cleanups for :func:`~unittest.setUpModule()` and
1106   :meth:`~unittest.TestCase.setUpClass()`.
1107   (Contributed by Lisa Roach in :issue:`24412`.)
1108
1109 * Several mock assert functions now also print a list of actual calls upon
1110   failure. (Contributed by Petter Strandmark in :issue:`35047`.)
1111
1112 * :mod:`unittest` module gained support for coroutines to be used as test cases
1113   with :class:`unittest.IsolatedAsyncioTestCase`.
1114   (Contributed by Andrew Svetlov in :issue:`32972`.)
1115
1116   Example::
1117
1118     import unittest
1119
1120
1121     class TestRequest(unittest.IsolatedAsyncioTestCase):
1122
1123         async def asyncSetUp(self):
1124             self.connection = await AsyncConnection()
1125
1126         async def test_get(self):
1127             response = await self.connection.get("https://example.com")
1128             self.assertEqual(response.status_code, 200)
1129
1130         async def asyncTearDown(self):
1131             await self.connection.close()
1132
1133
1134     if __name__ == "__main__":
1135         unittest.main()
1136
1137
1138 venv
1139 ----
1140
1141 * :mod:`venv` now includes an ``Activate.ps1`` script on all platforms for
1142   activating virtual environments under PowerShell Core 6.1.
1143   (Contributed by Brett Cannon in :issue:`32718`.)
1144
1145 weakref
1146 -------
1147
1148 * The proxy objects returned by :func:`weakref.proxy` now support the matrix
1149   multiplication operators ``@`` and ``@=`` in addition to the other
1150   numeric operators. (Contributed by Mark Dickinson in :issue:`36669`.)
1151
1152 xml
1153 ---
1154
1155 * As mitigation against DTD and external entity retrieval, the
1156   :mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
1157   external entities by default.
1158   (Contributed by Christian Heimes in :issue:`17239`.)
1159
1160 * The ``.find*()`` methods in the :mod:`xml.etree.ElementTree` module
1161   support wildcard searches like ``{*}tag`` which ignores the namespace
1162   and ``{namespace}*`` which returns all tags in the given namespace.
1163   (Contributed by Stefan Behnel in :issue:`28238`.)
1164
1165 * The :mod:`xml.etree.ElementTree` module provides a new function
1166   :func:`–xml.etree.ElementTree.canonicalize()` that implements C14N 2.0.
1167   (Contributed by Stefan Behnel in :issue:`13611`.)
1168
1169 * The target object of :class:`xml.etree.ElementTree.XMLParser` can
1170   receive namespace declaration events through the new callback methods
1171   ``start_ns()`` and ``end_ns()``.  Additionally, the
1172   :class:`xml.etree.ElementTree.TreeBuilder` target can be configured
1173   to process events about comments and processing instructions to include
1174   them in the generated tree.
1175   (Contributed by Stefan Behnel in :issue:`36676` and :issue:`36673`.)
1176
1177 Optimizations
1178 =============
1179
1180 * The :mod:`subprocess` module can now use the :func:`os.posix_spawn` function
1181   in some cases for better performance. Currently, it is only used on macOS
1182   and Linux (using glibc 2.24 or newer) if all these conditions are met:
1183
1184   * *close_fds* is false;
1185   * *preexec_fn*, *pass_fds*, *cwd* and *start_new_session* parameters
1186     are not set;
1187   * the *executable* path contains a directory.
1188
1189   (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
1190
1191 * :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
1192   :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
1193   "fast-copy" syscalls on Linux and macOS in order to copy the file
1194   more efficiently.
1195   "fast-copy" means that the copying operation occurs within the kernel,
1196   avoiding the use of userspace buffers in Python as in
1197   "``outfd.write(infd.read())``".
1198   On Windows :func:`shutil.copyfile` uses a bigger default buffer size (1 MiB
1199   instead of 16 KiB) and a :func:`memoryview`-based variant of
1200   :func:`shutil.copyfileobj` is used.
1201   The speedup for copying a 512 MiB file within the same partition is about
1202   +26% on Linux, +50% on macOS and +40% on Windows. Also, much less CPU cycles
1203   are consumed.
1204   See :ref:`shutil-platform-dependent-efficient-copy-operations` section.
1205   (Contributed by Giampaolo Rodola' in :issue:`33671`.)
1206
1207 * :func:`shutil.copytree` uses :func:`os.scandir` function and all copy
1208   functions depending from it use cached :func:`os.stat` values. The speedup
1209   for copying a directory with 8000 files is around +9% on Linux, +20% on
1210   Windows and +30% on a Windows SMB share. Also the number of :func:`os.stat`
1211   syscalls is reduced by 38% making :func:`shutil.copytree` especially faster
1212   on network filesystems. (Contributed by Giampaolo Rodola' in :issue:`33695`.)
1213
1214 * The default protocol in the :mod:`pickle` module is now Protocol 4,
1215   first introduced in Python 3.4.  It offers better performance and smaller
1216   size compared to Protocol 3 available since Python 3.0.
1217
1218 * Removed one ``Py_ssize_t`` member from ``PyGC_Head``.  All GC tracked
1219   objects (e.g. tuple, list, dict) size is reduced 4 or 8 bytes.
1220   (Contributed by Inada Naoki in :issue:`33597`)
1221
1222 * :class:`uuid.UUID` now uses ``__slots__`` to reduce its memory footprint.
1223
1224 * Improved performance of :func:`operator.itemgetter` by 33%.  Optimized
1225   argument handling and added a fast path for the common case of a single
1226   non-negative integer index into a tuple (which is the typical use case in
1227   the standard library).  (Contributed by Raymond Hettinger in
1228   :issue:`35664`.)
1229
1230 * Sped-up field lookups in :func:`collections.namedtuple`.  They are now more
1231   than two times faster, making them the fastest form of instance variable
1232   lookup in Python. (Contributed by Raymond Hettinger, Pablo Galindo, and
1233   Joe Jevnik, Serhiy Storchaka in :issue:`32492`.)
1234
1235 * The :class:`list` constructor does not overallocate the internal item buffer
1236   if the input iterable has a known length (the input implements ``__len__``).
1237   This makes the created list 12% smaller on average. (Contributed by
1238   Raymond Hettinger and Pablo Galindo in :issue:`33234`.)
1239
1240 * Doubled the speed of class variable writes.  When a non-dunder attribute
1241   was updated, there was an unnecessary call to update slots.
1242   (Contributed by Stefan Behnel, Pablo Galindo Salgado, Raymond Hettinger,
1243   Neil Schemenauer, and Serhiy Storchaka in :issue:`36012`.)
1244
1245 * Reduced an overhead of converting arguments passed to many builtin functions
1246   and methods.  This sped up calling some simple builtin functions and
1247   methods up to 20--50%.  (Contributed by Serhiy Storchaka in :issue:`23867`,
1248   :issue:`35582` and :issue:`36127`.)
1249
1250 * ``LOAD_GLOBAL`` instruction now uses new "per opcode cache" mechanism.
1251   It is about 40% faster now.  (Contributed by Yury Selivanov and Inada Naoki in
1252   :issue:`26219`.)
1253
1254
1255 Build and C API Changes
1256 =======================
1257
1258 * Default :data:`sys.abiflags` became an empty string: the ``m`` flag for
1259   pymalloc became useless (builds with and without pymalloc are ABI compatible)
1260   and so has been removed. (Contributed by Victor Stinner in :issue:`36707`.)
1261
1262   Example of changes:
1263
1264   * Only ``python3.8`` program is installed, ``python3.8m`` program is gone.
1265   * Only ``python3.8-config`` script is installed, ``python3.8m-config`` script
1266     is gone.
1267   * The ``m`` flag has been removed from the suffix of dynamic library
1268     filenames: extension modules in the standard library as well as those
1269     produced and installed by third-party packages, like those downloaded from
1270     PyPI. On Linux, for example, the Python 3.7 suffix
1271     ``.cpython-37m-x86_64-linux-gnu.so`` became
1272     ``.cpython-38-x86_64-linux-gnu.so`` in Python 3.8.
1273
1274 * The header files have been reorganized to better separate the different kinds
1275   of APIs:
1276
1277   * ``Include/*.h`` should be the portable public stable C API.
1278   * ``Include/cpython/*.h`` should be the unstable C API specific to CPython;
1279     public API, with some private API prefixed by ``_Py`` or ``_PY``.
1280   * ``Include/internal/*.h`` is the private internal C API very specific to
1281     CPython. This API comes with no backward compatibility warranty and should
1282     not be used outside CPython. It is only exposed for very specific needs
1283     like debuggers and profiles which has to access to CPython internals
1284     without calling functions. This API is now installed by ``make install``.
1285
1286   (Contributed by Victor Stinner in :issue:`35134` and :issue:`35081`,
1287   work initiated by Eric Snow in Python 3.7)
1288
1289 * Some macros have been converted to static inline functions: parameter types
1290   and return type are well defined, they don't have issues specific to macros,
1291   variables have a local scopes. Examples:
1292
1293   * :c:func:`Py_INCREF`, :c:func:`Py_DECREF`
1294   * :c:func:`Py_XINCREF`, :c:func:`Py_XDECREF`
1295   * :c:func:`PyObject_INIT`, :c:func:`PyObject_INIT_VAR`
1296   * Private functions: :c:func:`_PyObject_GC_TRACK`,
1297     :c:func:`_PyObject_GC_UNTRACK`, :c:func:`_Py_Dealloc`
1298
1299   (Contributed by Victor Stinner in :issue:`35059`.)
1300
1301 * The :c:func:`PyByteArray_Init` and :c:func:`PyByteArray_Fini` functions have
1302   been removed. They did nothing since Python 2.7.4 and Python 3.2.0, were
1303   excluded from the limited API (stable ABI), and were not documented.
1304   (Contributed by Victor Stinner in :issue:`35713`.)
1305
1306 * The result of :c:func:`PyExceptionClass_Name` is now of type
1307   ``const char *`` rather of ``char *``.
1308   (Contributed by Serhiy Storchaka in :issue:`33818`.)
1309
1310 * The duality of ``Modules/Setup.dist`` and ``Modules/Setup`` has been
1311   removed.  Previously, when updating the CPython source tree, one had
1312   to manually copy ``Modules/Setup.dist`` (inside the source tree) to
1313   ``Modules/Setup`` (inside the build tree) in order to reflect any changes
1314   upstream.  This was of a small benefit to packagers at the expense of
1315   a frequent annoyance to developers following CPython development, as
1316   forgetting to copy the file could produce build failures.
1317
1318   Now the build system always reads from ``Modules/Setup`` inside the source
1319   tree.  People who want to customize that file are encouraged to maintain
1320   their changes in a git fork of CPython or as patch files, as they would do
1321   for any other change to the source tree.
1322
1323   (Contributed by Antoine Pitrou in :issue:`32430`.)
1324
1325 * Functions that convert Python number to C integer like
1326   :c:func:`PyLong_AsLong` and argument parsing functions like
1327   :c:func:`PyArg_ParseTuple` with integer converting format units like ``'i'``
1328   will now use the :meth:`~object.__index__` special method instead of
1329   :meth:`~object.__int__`, if available.  The deprecation warning will be
1330   emitted for objects with the ``__int__()`` method but without the
1331   ``__index__()`` method (like :class:`~decimal.Decimal` and
1332   :class:`~fractions.Fraction`).  :c:func:`PyNumber_Check` will now return
1333   ``1`` for objects implementing ``__index__()``.
1334   :c:func:`PyNumber_Long`, :c:func:`PyNumber_Float` and
1335   :c:func:`PyFloat_AsDouble` also now use the ``__index__()`` method if
1336   available.
1337   (Contributed by Serhiy Storchaka in :issue:`36048` and :issue:`20092`.)
1338
1339 * Heap-allocated type objects will now increase their reference count
1340   in :c:func:`PyObject_Init` (and its parallel macro ``PyObject_INIT``)
1341   instead of in :c:func:`PyType_GenericAlloc`. Types that modify instance
1342   allocation or deallocation may need to be adjusted.
1343   (Contributed by Eddie Elizondo in :issue:`35810`.)
1344
1345 * The new function :c:func:`PyCode_NewWithPosOnlyArgs` allows to create
1346   code objects like :c:func:`PyCode_New`, but with an extra *posonlyargcount*
1347   parameter for indicating the number of positional-only arguments.
1348   (Contributed by Pablo Galindo in :issue:`37221`.)
1349
1350 * :c:func:`Py_SetPath` now sets :data:`sys.executable` to the program full
1351   path (:c:func:`Py_GetProgramFullPath`) rather than to the program name
1352   (:c:func:`Py_GetProgramName`).
1353   (Contributed by Victor Stinner in :issue:`38234`.)
1354
1355
1356 Deprecated
1357 ==========
1358
1359 * The distutils ``bdist_wininst`` command is now deprecated, use
1360   ``bdist_wheel`` (wheel packages) instead.
1361   (Contributed by Victor Stinner in :issue:`37481`.)
1362
1363 * Deprecated methods ``getchildren()`` and ``getiterator()`` in
1364   the :mod:`~xml.etree.ElementTree` module emit now a
1365   :exc:`DeprecationWarning` instead of :exc:`PendingDeprecationWarning`.
1366   They will be removed in Python 3.9.
1367   (Contributed by Serhiy Storchaka in :issue:`29209`.)
1368
1369 * Passing an object that is not an instance of
1370   :class:`concurrent.futures.ThreadPoolExecutor` to
1371   :meth:`asyncio.loop.set_default_executor()` is
1372   deprecated and will be prohibited in Python 3.9.
1373   (Contributed by Elvis Pranskevichus in :issue:`34075`.)
1374
1375 * The :meth:`__getitem__` methods of :class:`xml.dom.pulldom.DOMEventStream`,
1376   :class:`wsgiref.util.FileWrapper` and :class:`fileinput.FileInput` have been
1377   deprecated.
1378
1379   Implementations of these methods have been ignoring their *index* parameter,
1380   and returning the next item instead.
1381
1382   (Contributed by Berker Peksag in :issue:`9372`.)
1383
1384 * The :class:`typing.NamedTuple` class has deprecated the ``_field_types``
1385   attribute in favor of the ``__annotations__`` attribute which has the same
1386   information.  (Contributed by Raymond Hettinger in :issue:`36320`.)
1387
1388 * :mod:`ast` classes ``Num``, ``Str``, ``Bytes``, ``NameConstant`` and
1389   ``Ellipsis`` are considered deprecated and will be removed in future Python
1390   versions. :class:`~ast.Constant` should be used instead.
1391   (Contributed by Serhiy Storchaka in :issue:`32892`.)
1392
1393 * :class:`ast.NodeVisitor` methods ``visit_Num()``, ``visit_Str()``,
1394   ``visit_Bytes()``, ``visit_NameConstant()`` and ``visit_Ellipsis()`` are
1395   deprecated now and will not be called in future Python versions.
1396   Add the :meth:`~ast.NodeVisitor.visit_Constant` method to handle all
1397   constant nodes.
1398   (Contributed by Serhiy Storchaka in :issue:`36917`.)
1399
1400 * The following functions and methods are deprecated in the :mod:`gettext`
1401   module: :func:`~gettext.lgettext`, :func:`~gettext.ldgettext`,
1402   :func:`~gettext.lngettext` and :func:`~gettext.ldngettext`.
1403   They return encoded bytes, and it's possible that you will get unexpected
1404   Unicode-related exceptions if there are encoding problems with the
1405   translated strings. It's much better to use alternatives which return
1406   Unicode strings in Python 3. These functions have been broken for a long time.
1407
1408   Function :func:`~gettext.bind_textdomain_codeset`, methods
1409   :meth:`~gettext.NullTranslations.output_charset` and
1410   :meth:`~gettext.NullTranslations.set_output_charset`, and the *codeset*
1411   parameter of functions :func:`~gettext.translation` and
1412   :func:`~gettext.install` are also deprecated, since they are only used for
1413   for the ``l*gettext()`` functions.
1414
1415   (Contributed by Serhiy Storchaka in :issue:`33710`.)
1416
1417 * The :meth:`~threading.Thread.isAlive()` method of :class:`threading.Thread` has been deprecated.
1418   (Contributed by Dong-hee Na in :issue:`35283`.)
1419
1420 * Many builtin and extension functions that take integer arguments will
1421   now emit a deprecation warning for :class:`~decimal.Decimal`\ s,
1422   :class:`~fractions.Fraction`\ s and any other objects that can be converted
1423   to integers only with a loss (e.g. that have the :meth:`~object.__int__`
1424   method but do not have the :meth:`~object.__index__` method).  In future
1425   version they will be errors.
1426   (Contributed by Serhiy Storchaka in :issue:`36048`.)
1427
1428 * Deprecated passing the following arguments as keyword arguments:
1429
1430   - *func* in :func:`functools.partialmethod`, :func:`weakref.finalize`,
1431     :meth:`profile.Profile.runcall`, :meth:`cProfile.Profile.runcall`,
1432     :meth:`bdb.Bdb.runcall`, :meth:`trace.Trace.runfunc` and
1433     :func:`curses.wrapper`.
1434   - *function* in :meth:`unittest.TestCase.addCleanup`.
1435   - *fn* in the :meth:`~concurrent.futures.Executor.submit` method of
1436     :class:`concurrent.futures.ThreadPoolExecutor` and
1437     :class:`concurrent.futures.ProcessPoolExecutor`.
1438   - *callback* in :meth:`contextlib.ExitStack.callback`,
1439     :meth:`contextlib.AsyncExitStack.callback` and
1440     :meth:`contextlib.AsyncExitStack.push_async_callback`.
1441   - *c* and *typeid* in the :meth:`~multiprocessing.managers.Server.create`
1442     method of :class:`multiprocessing.managers.Server` and
1443     :class:`multiprocessing.managers.SharedMemoryServer`.
1444   - *obj* in :func:`weakref.finalize`.
1445
1446   In future releases of Python they will be :ref:`positional-only
1447   <positional-only_parameter>`.
1448   (Contributed by Serhiy Storchaka in :issue:`36492`.)
1449
1450
1451 API and Feature Removals
1452 ========================
1453
1454 The following features and APIs have been removed from Python 3.8:
1455
1456 * The :mod:`macpath` module, deprecated in Python 3.7, has been removed.
1457   (Contributed by Victor Stinner in :issue:`35471`.)
1458
1459 * The function :func:`platform.popen` has been removed, it was deprecated since
1460   Python 3.3: use :func:`os.popen` instead.
1461   (Contributed by Victor Stinner in :issue:`35345`.)
1462
1463 * The function :func:`time.clock` has been removed, it was deprecated since Python
1464   3.3: use :func:`time.perf_counter` or :func:`time.process_time` instead, depending
1465   on your requirements, to have a well defined behavior.
1466   (Contributed by Matthias Bussonnier in :issue:`36895`.)
1467
1468 * The ``pyvenv`` script has been removed in favor of ``python3.8 -m venv``
1469   to help eliminate confusion as to what Python interpreter the ``pyvenv``
1470   script is tied to. (Contributed by Brett Cannon in :issue:`25427`.)
1471
1472 * ``parse_qs``, ``parse_qsl``, and ``escape`` are removed from :mod:`cgi`
1473   module.  They are deprecated from Python 3.2 or older. They should be imported
1474   from the ``urllib.parse`` and ``html`` modules instead.
1475
1476 * ``filemode`` function is removed from :mod:`tarfile` module.
1477   It is not documented and deprecated since Python 3.3.
1478
1479 * The :class:`~xml.etree.ElementTree.XMLParser` constructor no longer accepts
1480   the *html* argument.  It never had effect and was deprecated in Python 3.4.
1481   All other parameters are now :ref:`keyword-only <keyword-only_parameter>`.
1482   (Contributed by Serhiy Storchaka in :issue:`29209`.)
1483
1484 * Removed the ``doctype()`` method of :class:`~xml.etree.ElementTree.XMLParser`.
1485   (Contributed by Serhiy Storchaka in :issue:`29209`.)
1486
1487 * "unicode_internal" codec is removed.
1488   (Contributed by Inada Naoki in :issue:`36297`.)
1489
1490 * The ``Cache`` and ``Statement`` objects of the :mod:`sqlite3` module are not
1491   exposed to the user.
1492   (Contributed by Aviv Palivoda in :issue:`30262`.)
1493
1494 * The ``bufsize`` keyword argument of :func:`fileinput.input` and
1495   :func:`fileinput.FileInput` which was ignored and deprecated since Python 3.6
1496   has been removed. :issue:`36952` (Contributed by Matthias Bussonnier)
1497
1498 * The functions :func:`sys.set_coroutine_wrapper` and
1499   :func:`sys.get_coroutine_wrapper` deprecated in Python 3.7 have been removed;
1500   :issue:`36933` (Contributed by Matthias Bussonnier)
1501
1502
1503 Porting to Python 3.8
1504 =====================
1505
1506 This section lists previously described changes and other bugfixes
1507 that may require changes to your code.
1508
1509
1510 Changes in Python behavior
1511 --------------------------
1512
1513 * Yield expressions (both ``yield`` and ``yield from`` clauses) are now disallowed
1514   in comprehensions and generator expressions (aside from the iterable expression
1515   in the leftmost :keyword:`!for` clause).
1516   (Contributed by Serhiy Storchaka in :issue:`10544`.)
1517
1518 * The compiler now produces a :exc:`SyntaxWarning` when identity checks
1519   (``is`` and ``is not``) are used with certain types of literals
1520   (e.g. strings, ints).  These can often work by accident in CPython,
1521   but are not guaranteed by the language spec.  The warning advises users
1522   to use equality tests (``==`` and ``!=``) instead.
1523   (Contributed by Serhiy Storchaka in :issue:`34850`.)
1524
1525 * The CPython interpreter can swallow exceptions in some circumstances.
1526   In Python 3.8 this happens in less cases.  In particular, exceptions
1527   raised when getting the attribute from the type dictionary are no longer
1528   ignored.  (Contributed by Serhiy Storchaka in :issue:`35459`.)
1529
1530 * Removed ``__str__`` implementations from builtin types :class:`bool`,
1531   :class:`int`, :class:`float`, :class:`complex` and few classes from
1532   the standard library.  They now inherit ``__str__()`` from :class:`object`.
1533   As result, defining the ``__repr__()`` method in the subclass of these
1534   classes will affect their string representation.
1535   (Contributed by Serhiy Storchaka in :issue:`36793`.)
1536
1537 * On AIX, :attr:`sys.platform` doesn't contain the major version anymore.
1538   It is always ``'aix'``, instead of ``'aix3'`` .. ``'aix7'``.  Since
1539   older Python versions include the version number, it is recommended to
1540   always use the ``sys.platform.startswith('aix')``.
1541   (Contributed by M. Felt in :issue:`36588`.)
1542
1543 * :c:func:`PyEval_AcquireLock` and :c:func:`PyEval_AcquireThread` now
1544   terminate the current thread if called while the interpreter is
1545   finalizing, making them consistent with :c:func:`PyEval_RestoreThread`,
1546   :c:func:`Py_END_ALLOW_THREADS`, and :c:func:`PyGILState_Ensure`. If this
1547   behaviour is not desired, guard the call by checking :c:func:`_Py_IsFinalizing`
1548   or :c:func:`sys.is_finalizing`.
1549
1550 Changes in the Python API
1551 -------------------------
1552
1553 * The :func:`os.getcwdb` function now uses the UTF-8 encoding on Windows,
1554   rather than the ANSI code page: see :pep:`529` for the rationale. The
1555   function is no longer deprecated on Windows.
1556   (Contributed by Victor Stinner in :issue:`37412`.)
1557
1558 * :class:`subprocess.Popen` can now use :func:`os.posix_spawn` in some cases
1559   for better performance. On Windows Subsystem for Linux and QEMU User
1560   Emulation, Popen constructor using :func:`os.posix_spawn` no longer raise an
1561   exception on errors like missing program, but the child process fails with a
1562   non-zero :attr:`~Popen.returncode`.
1563   (Contributed by Joannah Nanjekye and Victor Stinner in :issue:`35537`.)
1564
1565 * The *preexec_fn* argument of * :class:`subprocess.Popen` is no longer
1566   compatible with subinterpreters. The use of the parameter in a
1567   subinterpreter now raises :exc:`RuntimeError`.
1568   (Contributed by Eric Snow in :issue:`34651`, modified by Christian Heimes
1569   in :issue:`37951`.)
1570
1571 * The :meth:`imap.IMAP4.logout` method no longer ignores silently arbitrary
1572   exceptions.
1573
1574 * The function :func:`platform.popen` has been removed, it was deprecated since
1575   Python 3.3: use :func:`os.popen` instead.
1576   (Contributed by Victor Stinner in :issue:`35345`.)
1577
1578 * The :func:`statistics.mode` function no longer raises an exception
1579   when given multimodal data.  Instead, it returns the first mode
1580   encountered in the input data.  (Contributed by Raymond Hettinger
1581   in :issue:`35892`.)
1582
1583 * The :meth:`~tkinter.ttk.Treeview.selection` method of the
1584   :class:`tkinter.ttk.Treeview` class no longer takes arguments.  Using it with
1585   arguments for changing the selection was deprecated in Python 3.6.  Use
1586   specialized methods like :meth:`~tkinter.ttk.Treeview.selection_set` for
1587   changing the selection.  (Contributed by Serhiy Storchaka in :issue:`31508`.)
1588
1589 * The :meth:`writexml`, :meth:`toxml` and :meth:`toprettyxml` methods of the
1590   :mod:`xml.dom.minidom` module, and :mod:`xml.etree` now preserve the attribute
1591   order specified by the user.
1592   (Contributed by Diego Rojas and Raymond Hettinger in :issue:`34160`.)
1593
1594 * A :mod:`dbm.dumb` database opened with flags ``'r'`` is now read-only.
1595   :func:`dbm.dumb.open` with flags ``'r'`` and ``'w'`` no longer creates
1596   a database if it does not exist.
1597   (Contributed by Serhiy Storchaka in :issue:`32749`.)
1598
1599 * The ``doctype()`` method defined in a subclass of
1600   :class:`~xml.etree.ElementTree.XMLParser` will no longer be called and will
1601   cause emitting a :exc:`RuntimeWarning` instead of a :exc:`DeprecationWarning`.
1602   Define the :meth:`doctype() <xml.etree.ElementTree.TreeBuilder.doctype>`
1603   method on a target for handling an XML doctype declaration.
1604   (Contributed by Serhiy Storchaka in :issue:`29209`.)
1605
1606 * A :exc:`RuntimeError` is now raised when the custom metaclass doesn't
1607   provide the ``__classcell__`` entry in the namespace passed to
1608   ``type.__new__``.  A :exc:`DeprecationWarning` was emitted in Python
1609   3.6--3.7.  (Contributed by Serhiy Storchaka in :issue:`23722`.)
1610
1611 * The :class:`cProfile.Profile` class can now be used as a context
1612   manager. (Contributed by Scott Sanderson in :issue:`29235`.)
1613
1614 * :func:`shutil.copyfile`, :func:`shutil.copy`, :func:`shutil.copy2`,
1615   :func:`shutil.copytree` and :func:`shutil.move` use platform-specific
1616   "fast-copy" syscalls (see
1617   :ref:`shutil-platform-dependent-efficient-copy-operations` section).
1618
1619 * :func:`shutil.copyfile` default buffer size on Windows was changed from
1620   16 KiB to 1 MiB.
1621
1622 * The ``PyGC_Head`` struct has changed completely.  All code that touched the
1623   struct member should be rewritten.  (See :issue:`33597`)
1624
1625 * The ``PyInterpreterState`` struct has been moved into the "internal"
1626   header files (specifically Include/internal/pycore_pystate.h).  An
1627   opaque ``PyInterpreterState`` is still available as part of the public
1628   API (and stable ABI).  The docs indicate that none of the struct's
1629   fields are public, so we hope no one has been using them.  However,
1630   if you do rely on one or more of those private fields and have no
1631   alternative then please open a BPO issue.  We'll work on helping
1632   you adjust (possibly including adding accessor functions to the
1633   public API).  (See :issue:`35886`.)
1634
1635 * Asyncio tasks can now be named, either by passing the ``name`` keyword
1636   argument to :func:`asyncio.create_task` or
1637   the :meth:`~asyncio.loop.create_task` event loop method, or by
1638   calling the :meth:`~asyncio.Task.set_name` method on the task object. The
1639   task name is visible in the ``repr()`` output of :class:`asyncio.Task` and
1640   can also be retrieved using the :meth:`~asyncio.Task.get_name` method.
1641
1642 * The :meth:`mmap.flush() <mmap.mmap.flush>` method now returns ``None`` on
1643   success and raises an exception on error under all platforms.  Previously,
1644   its behavior was platform-depended: a nonzero value was returned on success;
1645   zero was returned on error under Windows.  A zero value was returned on
1646   success; an exception was raised on error under Unix.
1647   (Contributed by Berker Peksag in :issue:`2122`.)
1648
1649 * :mod:`xml.dom.minidom` and :mod:`xml.sax` modules no longer process
1650   external entities by default.
1651   (Contributed by Christian Heimes in :issue:`17239`.)
1652
1653 * Deleting a key from a read-only :mod:`dbm` database (:mod:`dbm.dumb`,
1654   :mod:`dbm.gnu` or :mod:`dbm.ndbm`) raises :attr:`error` (:exc:`dbm.dumb.error`,
1655   :exc:`dbm.gnu.error` or :exc:`dbm.ndbm.error`) instead of :exc:`KeyError`.
1656   (Contributed by Xiang Zhang in :issue:`33106`.)
1657
1658 * :func:`~os.path.expanduser` on Windows now prefers the :envvar:`USERPROFILE`
1659   environment variable and does not use :envvar:`HOME`, which is not normally
1660   set for regular user accounts.
1661
1662 * The Exception :class:`asyncio.CancelledError` now inherits from
1663   :class:`BaseException` rather than a :class:`Exception`.
1664   (Contributed by Yury Selivanov in :issue:`13528`.)
1665
1666 .. _bpo-36085-whatsnew:
1667
1668 * DLL dependencies for extension modules and DLLs loaded with :mod:`ctypes` on
1669   Windows are now resolved more securely. Only the system paths, the directory
1670   containing the DLL or PYD file, and directories added with
1671   :func:`~os.add_dll_directory` are searched for load-time dependencies.
1672   Specifically, :envvar:`PATH` and the current working directory are no longer
1673   used, and modifications to these will no longer have any effect on normal DLL
1674   resolution. If your application relies on these mechanisms, you should check
1675   for :func:`~os.add_dll_directory` and if it exists, use it to add your DLLs
1676   directory while loading your library. Note that Windows 7 users will need to
1677   ensure that Windows Update KB2533625 has been installed (this is also verified
1678   by the installer).
1679   (See :issue:`36085`.)
1680
1681 * The header files and functions related to pgen have been removed after its
1682   replacement by a pure Python implementation. (Contributed by Pablo Galindo
1683   in :issue:`36623`.)
1684
1685 * :class:`types.CodeType` has a new parameter in the second position of the
1686   constructor (*posonlyargcount*) to support positional-only arguments defined
1687   in :pep:`570`. The first argument (*argcount*) now represents the total
1688   number of positional arguments (including positional-only arguments). A new
1689   ``replace()`` method of :class:`types.CodeType` can be used to make the code
1690   future-proof.
1691
1692
1693 Changes in the C API
1694 --------------------
1695
1696 * The :c:type:`PyCompilerFlags` structure gets a new *cf_feature_version*
1697   field. It should be initialized to ``PY_MINOR_VERSION``. The field is ignored
1698   by default, it is used if and only if ``PyCF_ONLY_AST`` flag is set in
1699   *cf_flags*.
1700
1701 * The :c:func:`PyEval_ReInitThreads` function has been removed from the C API.
1702   It should not be called explicitly: use :c:func:`PyOS_AfterFork_Child`
1703   instead.
1704   (Contributed by Victor Stinner in :issue:`36728`.)
1705
1706 * On Unix, C extensions are no longer linked to libpython except on Android
1707   and Cygwin. When Python is embedded, ``libpython`` must not be loaded with
1708   ``RTLD_LOCAL``, but ``RTLD_GLOBAL`` instead. Previously, using
1709   ``RTLD_LOCAL``, it was already not possible to load C extensions which
1710   were not linked to ``libpython``, like C extensions of the standard
1711   library built by the ``*shared*`` section of ``Modules/Setup``.
1712   (Contributed by Victor Stinner in :issue:`21536`.)
1713
1714 * Use of ``#`` variants of formats in parsing or building value (e.g.
1715   :c:func:`PyArg_ParseTuple`, :c:func:`Py_BuildValue`, :c:func:`PyObject_CallFunction`,
1716   etc.) without ``PY_SSIZE_T_CLEAN`` defined raises ``DeprecationWarning`` now.
1717   It will be removed in 3.10 or 4.0.  Read :ref:`arg-parsing` for detail.
1718   (Contributed by Inada Naoki in :issue:`36381`.)
1719
1720 * Instances of heap-allocated types (such as those created with
1721   :c:func:`PyType_FromSpec`) hold a reference to their type object.
1722   Increasing the reference count of these type objects has been moved from
1723   :c:func:`PyType_GenericAlloc` to the more low-level functions,
1724   :c:func:`PyObject_Init` and :c:func:`PyObject_INIT`.
1725   This makes types created through :c:func:`PyType_FromSpec` behave like
1726   other classes in managed code.
1727
1728   Statically allocated types are not affected.
1729
1730   For the vast majority of cases, there should be no side effect.
1731   However, types that manually increase the reference count after allocating
1732   an instance (perhaps to work around the bug) may now become immortal.
1733   To avoid this, these classes need to call Py_DECREF on the type object
1734   during instance deallocation.
1735
1736   To correctly port these types into 3.8, please apply the following
1737   changes:
1738
1739   * Remove :c:macro:`Py_INCREF` on the type object after allocating an
1740     instance - if any.
1741     This may happen after calling :c:func:`PyObject_New`,
1742     :c:func:`PyObject_NewVar`, :c:func:`PyObject_GC_New`,
1743     :c:func:`PyObject_GC_NewVar`, or any other custom allocator that uses
1744     :c:func:`PyObject_Init` or :c:func:`PyObject_INIT`.
1745
1746     Example::
1747
1748         static foo_struct *
1749         foo_new(PyObject *type) {
1750             foo_struct *foo = PyObject_GC_New(foo_struct, (PyTypeObject *) type);
1751             if (foo == NULL)
1752                 return NULL;
1753         #if PY_VERSION_HEX < 0x03080000
1754             // Workaround for Python issue 35810; no longer necessary in Python 3.8
1755             PY_INCREF(type)
1756         #endif
1757             return foo;
1758         }
1759
1760   * Ensure that all custom ``tp_dealloc`` functions of heap-allocated types
1761     decrease the type's reference count.
1762
1763     Example::
1764
1765         static void
1766         foo_dealloc(foo_struct *instance) {
1767             PyObject *type = Py_TYPE(instance);
1768             PyObject_GC_Del(instance);
1769         #if PY_VERSION_HEX >= 0x03080000
1770             // This was not needed before Python 3.8 (Python issue 35810)
1771             Py_DECREF(type);
1772         #endif
1773         }
1774
1775   (Contributed by Eddie Elizondo in :issue:`35810`.)
1776
1777 * The :c:macro:`Py_DEPRECATED()` macro has been implemented for MSVC.
1778   The macro now must be placed before the symbol name.
1779
1780   Example::
1781
1782       Py_DEPRECATED(3.8) PyAPI_FUNC(int) Py_OldFunction(void);
1783
1784   (Contributed by Zackery Spytz in :issue:`33407`.)
1785
1786 * The interpreter does not pretend to support binary compatibility of
1787   extension types across feature releases, anymore.  A :c:type:`PyTypeObject`
1788   exported by a third-party extension module is supposed to have all the
1789   slots expected in the current Python version, including
1790   :c:member:`~PyTypeObject.tp_finalize` (:const:`Py_TPFLAGS_HAVE_FINALIZE`
1791   is not checked anymore before reading :c:member:`~PyTypeObject.tp_finalize`).
1792
1793   (Contributed by Antoine Pitrou in :issue:`32388`.)
1794
1795 * The :c:func:`PyCode_New` has a new parameter in the second position (*posonlyargcount*)
1796   to support :pep:`570`, indicating the number of positional-only arguments.
1797
1798 * The functions :c:func:`PyNode_AddChild` and :c:func:`PyParser_AddToken` now accept
1799   two additional ``int`` arguments *end_lineno* and *end_col_offset*.
1800
1801 .. highlight:: shell
1802
1803 * The :file:`libpython38.a` file to allow MinGW tools to link directly against
1804   :file:`python38.dll` is no longer included in the regular Windows distribution.
1805   If you require this file, it may be generated with the ``gendef`` and
1806   ``dlltool`` tools, which are part of the MinGW binutils package::
1807
1808       gendef python38.dll > tmp.def
1809       dlltool --dllname python38.dll --def tmp.def --output-lib libpython38.a
1810
1811   The location of an installed :file:`pythonXY.dll` will depend on the
1812   installation options and the version and language of Windows. See
1813   :ref:`using-on-windows` for more information. The resulting library should be
1814   placed in the same directory as :file:`pythonXY.lib`, which is generally the
1815   :file:`libs` directory under your Python installation.
1816
1817 .. highlight:: python3
1818
1819
1820 CPython bytecode changes
1821 ------------------------
1822
1823 * The interpreter loop  has been simplified by moving the logic of unrolling
1824   the stack of blocks into the compiler.  The compiler emits now explicit
1825   instructions for adjusting the stack of values and calling the
1826   cleaning-up code for :keyword:`break`, :keyword:`continue` and
1827   :keyword:`return`.
1828
1829   Removed opcodes :opcode:`BREAK_LOOP`, :opcode:`CONTINUE_LOOP`,
1830   :opcode:`SETUP_LOOP` and :opcode:`SETUP_EXCEPT`.  Added new opcodes
1831   :opcode:`ROT_FOUR`, :opcode:`BEGIN_FINALLY`, :opcode:`CALL_FINALLY` and
1832   :opcode:`POP_FINALLY`.  Changed the behavior of :opcode:`END_FINALLY`
1833   and :opcode:`WITH_CLEANUP_START`.
1834
1835   (Contributed by Mark Shannon, Antoine Pitrou and Serhiy Storchaka in
1836   :issue:`17611`.)
1837
1838 * Added new opcode :opcode:`END_ASYNC_FOR` for handling exceptions raised
1839   when awaiting a next item in an :keyword:`async for` loop.
1840   (Contributed by Serhiy Storchaka in :issue:`33041`.)
1841
1842 * The :opcode:`MAP_ADD` now expects the value as the first element in the
1843   stack and the key as the second element. This change was made so the key
1844   is always evaluated before the value in dictionary comprehensions, as
1845   proposed by :pep:`572`. (Contributed by Jörn Heissler in :issue:`35224`.)
1846
1847
1848 Demos and Tools
1849 ---------------
1850
1851 * Added a benchmark script for timing various ways to access variables:
1852   ``Tools/scripts/var_access_benchmark.py``.
1853   (Contributed by Raymond Hettinger in :issue:`35884`.)