-
-
Notifications
You must be signed in to change notification settings - Fork 31k
/
Copy path3.8.rst
2360 lines (1754 loc) · 92.6 KB
/
3.8.rst
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
****************************
What's New In Python 3.8
****************************
.. Rules for maintenance:
* Anyone can add text to this document. Do not spend very much time
on the wording of your changes, because your text will probably
get rewritten to some degree.
* The maintainer will go through Misc/NEWS periodically and add
changes; it's therefore more important to add your changes to
Misc/NEWS than to this file.
* This is not a complete list of every single change; completeness
is the purpose of Misc/NEWS. Some changes I consider too small
or esoteric to include. If such a change is added to the text,
I'll just remove it. (This is another reason you shouldn't spend
too much time on writing your addition.)
* If you want to draw your new text to the attention of the
maintainer, add 'XXX' to the beginning of the paragraph or
section.
* It's OK to just add a fragmentary note about a change. For
example: "XXX Describe the transmogrify() function added to the
socket module." The maintainer will research the change and
write the necessary text.
* You can comment out your additions if you like, but it's not
necessary (especially when a final release is some months away).
* Credit the author of a patch or bugfix. Just the name is
sufficient; the e-mail address isn't necessary.
* It's helpful to add the bug/patch number as a comment:
XXX Describe the transmogrify() function added to the socket
module.
(Contributed by P.Y. Developer in :issue:`12345`.)
This saves the maintainer the effort of going through the Git log
when researching a change.
:Editor: Raymond Hettinger
This article explains the new features in Python 3.8, compared to 3.7.
Python 3.8 was released on October 14, 2019.
For full details, see the :ref:`changelog <changelog>`.
.. testsetup::
from datetime import date
from math import cos, radians
from unicodedata import normalize
import re
import math
Summary -- Release highlights
=============================
.. This section singles out the most important changes in Python 3.8.
Brevity is key.
.. PEP-sized items next.
New Features
============
Assignment expressions
----------------------
There is new syntax ``:=`` that assigns values to variables as part of a larger
expression. It is affectionately known as "the walrus operator" due to
its resemblance to `the eyes and tusks of a walrus
<https://en.wikipedia.org/wiki/Walrus#/media/File:Pacific_Walrus_-_Bull_(8247646168).jpg>`_.
In this example, the assignment expression helps avoid calling
:func:`len` twice::
if (n := len(a)) > 10:
print(f"List is too long ({n} elements, expected <= 10)")
A similar benefit arises during regular expression matching where
match objects are needed twice, once to test whether a match
occurred and another to extract a subgroup::
discount = 0.0
if (mo := re.search(r'(\d+)% discount', advertisement)):
discount = float(mo.group(1)) / 100.0
The operator is also useful with while-loops that compute
a value to test loop termination and then need that same
value again in the body of the loop::
# Loop over fixed length blocks
while (block := f.read(256)) != '':
process(block)
Another motivating use case arises in list comprehensions where
a value computed in a filtering condition is also needed in
the expression body::
[clean_name.title() for name in names
if (clean_name := normalize('NFC', name)) in allowed_names]
Try to limit use of the walrus operator to clean cases that reduce
complexity and improve readability.
See :pep:`572` for a full description.
(Contributed by Emily Morehouse in :issue:`35224`.)
Positional-only parameters
--------------------------
There is a new function parameter syntax ``/`` to indicate that some
function parameters must be specified positionally and cannot be used as
keyword arguments. This is the same notation shown by ``help()`` for C
functions annotated with Larry Hastings'
`Argument Clinic <https://devguide.python.org/development-tools/clinic/>`__ tool.
In the following example, parameters *a* and *b* are positional-only,
while *c* or *d* can be positional or keyword, and *e* or *f* are
required to be keywords::
def f(a, b, /, c, d, *, e, f):
print(a, b, c, d, e, f)
The following is a valid call::
f(10, 20, 30, d=40, e=50, f=60)
However, these are invalid calls::
f(10, b=20, c=30, d=40, e=50, f=60) # b cannot be a keyword argument
f(10, 20, 30, 40, 50, f=60) # e must be a keyword argument
One use case for this notation is that it allows pure Python functions
to fully emulate behaviors of existing C coded functions. For example,
the built-in :func:`divmod` function does not accept keyword arguments::
def divmod(a, b, /):
"Emulate the built in divmod() function"
return (a // b, a % b)
Another use case is to preclude keyword arguments when the parameter
name is not helpful. For example, the builtin :func:`len` function has
the signature ``len(obj, /)``. This precludes awkward calls such as::
len(obj='hello') # The "obj" keyword argument impairs readability
A further benefit of marking a parameter as positional-only is that it
allows the parameter name to be changed in the future without risk of
breaking client code. For example, in the :mod:`statistics` module, the
parameter name *dist* may be changed in the future. This was made
possible with the following function specification::
def quantiles(dist, /, *, n=4, method='exclusive')
...
Since the parameters to the left of ``/`` are not exposed as possible
keywords, the parameters names remain available for use in ``**kwargs``::
>>> def f(a, b, /, **kwargs):
... print(a, b, kwargs)
...
>>> f(10, 20, a=1, b=2, c=3) # a and b are used in two ways
10 20 {'a': 1, 'b': 2, 'c': 3}
This greatly simplifies the implementation of functions and methods
that need to accept arbitrary keyword arguments. For example, here
is an excerpt from code in the :mod:`collections` module::
class Counter(dict):
def __init__(self, iterable=None, /, **kwds):
# Note "iterable" is a possible keyword argument
See :pep:`570` for a full description.
(Contributed by Pablo Galindo in :issue:`36540`.)
.. TODO: Pablo will sprint on docs at PyCon US 2019.
Parallel filesystem cache for compiled bytecode files
-----------------------------------------------------
The new :envvar:`PYTHONPYCACHEPREFIX` setting (also available as
:option:`-X` ``pycache_prefix``) configures the implicit bytecode
cache to use a separate parallel filesystem tree, rather than
the default ``__pycache__`` subdirectories within each source
directory.
The location of the cache is reported in :data:`sys.pycache_prefix`
(:const:`None` indicates the default location in ``__pycache__``
subdirectories).
(Contributed by Carl Meyer in :issue:`33499`.)
Debug build uses the same ABI as release build
-----------------------------------------------
Python now uses the same ABI whether it's built in release or debug mode. On
Unix, when Python is built in debug mode, it is now possible to load C
extensions built in release mode and C extensions built using the stable ABI.
Release builds and :ref:`debug builds <debug-build>` are now ABI compatible: defining the
``Py_DEBUG`` macro no longer implies the ``Py_TRACE_REFS`` macro, which
introduces the only ABI incompatibility. The ``Py_TRACE_REFS`` macro, which
adds the :func:`sys.getobjects` function and the :envvar:`PYTHONDUMPREFS`
environment variable, can be set using the new :option:`./configure
--with-trace-refs <--with-trace-refs>` build option.
(Contributed by Victor Stinner in :issue:`36465`.)
On Unix, C extensions are no longer linked to libpython except on Android
and Cygwin.
It is now possible
for a statically linked Python to load a C extension built using a shared
library Python.
(Contributed by Victor Stinner in :issue:`21536`.)
On Unix, when Python is built in debug mode, import now also looks for C
extensions compiled in release mode and for C extensions compiled with the
stable ABI.
(Contributed by Victor Stinner in :issue:`36722`.)
To embed Python into an application, a new ``--embed`` option must be passed to
``python3-config --libs --embed`` to get ``-lpython3.8`` (link the application
to libpython). To support both 3.8 and older, try ``python3-config --libs
--embed`` first and fallback to ``python3-config --libs`` (without ``--embed``)
if the previous command fails.
Add a pkg-config ``python-3.8-embed`` module to embed Python into an
application: ``pkg-config python-3.8-embed --libs`` includes ``-lpython3.8``.
To support both 3.8 and older, try ``pkg-config python-X.Y-embed --libs`` first
and fallback to ``pkg-config python-X.Y --libs`` (without ``--embed``) if the
previous command fails (replace ``X.Y`` with the Python version).
On the other hand, ``pkg-config python3.8 --libs`` no longer contains
``-lpython3.8``. C extensions must not be linked to libpython (except on
Android and Cygwin, whose cases are handled by the script);
this change is backward incompatible on purpose.
(Contributed by Victor Stinner in :issue:`36721`.)
.. _bpo-36817-whatsnew:
f-strings support ``=`` for self-documenting expressions and debugging
----------------------------------------------------------------------
Added an ``=`` specifier to :term:`f-string`\s. An f-string such as
``f'{expr=}'`` will expand to the text of the expression, an equal sign,
then the representation of the evaluated expression. For example:
>>> user = 'eric_idle'
>>> member_since = date(1975, 7, 31)
>>> f'{user=} {member_since=}'
"user='eric_idle' member_since=datetime.date(1975, 7, 31)"
The usual :ref:`f-string format specifiers <f-strings>` allow more
control over how the result of the expression is displayed::
>>> delta = date.today() - member_since
>>> f'{user=!s} {delta.days=:,d}'
'user=eric_idle delta.days=16,075'
The ``=`` specifier will display the whole expression so that
calculations can be shown::
>>> print(f'{theta=} {cos(radians(theta))=:.3f}')
theta=30 cos(radians(theta))=0.866
(Contributed by Eric V. Smith and Larry Hastings in :issue:`36817`.)
PEP 578: Python Runtime Audit Hooks
-----------------------------------
The PEP adds an Audit Hook and Verified Open Hook. Both are available from
Python and native code, allowing applications and frameworks written in pure
Python code to take advantage of extra notifications, while also allowing
embedders or system administrators to deploy builds of Python where auditing is
always enabled.
See :pep:`578` for full details.
PEP 587: Python Initialization Configuration
--------------------------------------------
The :pep:`587` adds a new C API to configure the Python Initialization
providing finer control on the whole configuration and better error reporting.
New structures:
* :c:type:`PyConfig`
* :c:type:`PyPreConfig`
* :c:type:`PyStatus`
* :c:type:`PyWideStringList`
New functions:
* :c:func:`PyConfig_Clear`
* :c:func:`PyConfig_InitIsolatedConfig`
* :c:func:`PyConfig_InitPythonConfig`
* :c:func:`PyConfig_Read`
* :c:func:`PyConfig_SetArgv`
* :c:func:`PyConfig_SetBytesArgv`
* :c:func:`PyConfig_SetBytesString`
* :c:func:`PyConfig_SetString`
* :c:func:`PyPreConfig_InitIsolatedConfig`
* :c:func:`PyPreConfig_InitPythonConfig`
* :c:func:`PyStatus_Error`
* :c:func:`PyStatus_Exception`
* :c:func:`PyStatus_Exit`
* :c:func:`PyStatus_IsError`
* :c:func:`PyStatus_IsExit`
* :c:func:`PyStatus_NoMemory`
* :c:func:`PyStatus_Ok`
* :c:func:`PyWideStringList_Append`
* :c:func:`PyWideStringList_Insert`
* :c:func:`Py_BytesMain`
* :c:func:`Py_ExitStatusException`
* :c:func:`Py_InitializeFromConfig`
* :c:func:`Py_PreInitialize`
* :c:func:`Py_PreInitializeFromArgs`
* :c:func:`Py_PreInitializeFromBytesArgs`
* :c:func:`Py_RunMain`
This PEP also adds ``_PyRuntimeState.preconfig`` (:c:type:`PyPreConfig` type)
and ``PyInterpreterState.config`` (:c:type:`PyConfig` type) fields to these
internal structures. ``PyInterpreterState.config`` becomes the new
reference configuration, replacing global configuration variables and
other private variables.
See :ref:`Python Initialization Configuration <init-config>` for the
documentation.
See :pep:`587` for a full description.
(Contributed by Victor Stinner in :issue:`36763`.)
PEP 590: Vectorcall: a fast calling protocol for CPython
--------------------------------------------------------
:ref:`vectorcall` is added to the Python/C API.
It is meant to formalize existing optimizations which were already done
for various classes.
Any :ref:`static type <static-types>` implementing a callable can use this
protocol.
This is currently provisional.
The aim is to make it fully public in Python 3.9.
See :pep:`590` for a full description.
(Contributed by Jeroen Demeyer, Mark Shannon and Petr Viktorin in :issue:`36974`.)
Pickle protocol 5 with out-of-band data buffers
-----------------------------------------------
When :mod:`pickle` is used to transfer large data between Python processes
in order to take advantage of multi-core or multi-machine processing,
it is important to optimize the transfer by reducing memory copies, and
possibly by applying custom techniques such as data-dependent compression.
The :mod:`pickle` protocol 5 introduces support for out-of-band buffers
where :pep:`3118`-compatible data can be transmitted separately from the
main pickle stream, at the discretion of the communication layer.
See :pep:`574` for a full description.
(Contributed by Antoine Pitrou in :issue:`36785`.)
Other Language Changes
======================
* A :keyword:`continue` statement was illegal in the :keyword:`finally` clause
due to a problem with the implementation. In Python 3.8 this restriction
was lifted.
(Contributed by Serhiy Storchaka in :issue:`32489`.)
* The :class:`bool`, :class:`int`, and :class:`fractions.Fraction` types
now have an :meth:`~int.as_integer_ratio` method like that found in
:class:`float` and :class:`decimal.Decimal`. This minor API extension
makes it possible to write ``numerator, denominator =
x.as_integer_ratio()`` and have it work across multiple numeric types.
(Contributed by Lisa Roach in :issue:`33073` and Raymond Hettinger in
:issue:`37819`.)
* Constructors of :class:`int`, :class:`float` and :class:`complex` will now
use the :meth:`~object.__index__` special method, if available and the
corresponding method :meth:`~object.__int__`, :meth:`~object.__float__`
or :meth:`~object.__complex__` is not available.
(Contributed by Serhiy Storchaka in :issue:`20092`.)
* Added support of :samp:`\\N\\{{name}\\}` escapes in :mod:`regular expressions <re>`::
>>> notice = 'Copyright © 2019'
>>> copyright_year_pattern = re.compile(r'\N{copyright sign}\s*(\d{4})')
>>> int(copyright_year_pattern.search(notice).group(1))
2019
(Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.)
* Dict and dictviews are now iterable in reversed insertion order using
:func:`reversed`. (Contributed by Rémi Lapeyre in :issue:`33462`.)
* The syntax allowed for keyword names in function calls was further
restricted. In particular, ``f((keyword)=arg)`` is no longer allowed. It was
never intended to permit more than a bare name on the left-hand side of a
keyword argument assignment term.
(Contributed by Benjamin Peterson in :issue:`34641`.)
* Generalized iterable unpacking in :keyword:`yield` and
:keyword:`return` statements no longer requires enclosing parentheses.
This brings the *yield* and *return* syntax into better agreement with
normal assignment syntax::
>>> def parse(family):
lastname, *members = family.split()
return lastname.upper(), *members
>>> parse('simpsons homer marge bart lisa maggie')
('SIMPSONS', 'homer', 'marge', 'bart', 'lisa', 'maggie')
(Contributed by David Cuthbert and Jordan Chapman in :issue:`32117`.)
* When a comma is missed in code such as ``[(10, 20) (30, 40)]``, the
compiler displays a :exc:`SyntaxWarning` with a helpful suggestion.
This improves on just having a :exc:`TypeError` indicating that the
first tuple was not callable. (Contributed by Serhiy Storchaka in
:issue:`15248`.)
* Arithmetic operations between subclasses of :class:`datetime.date` or
:class:`datetime.datetime` and :class:`datetime.timedelta` objects now return
an instance of the subclass, rather than the base class. This also affects
the return type of operations whose implementation (directly or indirectly)
uses :class:`datetime.timedelta` arithmetic, such as
:meth:`~datetime.datetime.astimezone`.
(Contributed by Paul Ganssle in :issue:`32417`.)
* When the Python interpreter is interrupted by Ctrl-C (SIGINT) and the
resulting :exc:`KeyboardInterrupt` exception is not caught, the Python process
now exits via a SIGINT signal or with the correct exit code such that the
calling process can detect that it died due to a Ctrl-C. Shells on POSIX
and Windows use this to properly terminate scripts in interactive sessions.
(Contributed by Google via Gregory P. Smith in :issue:`1054041`.)
* Some advanced styles of programming require updating the
:class:`types.CodeType` object for an existing function. Since code
objects are immutable, a new code object needs to be created, one
that is modeled on the existing code object. With 19 parameters,
this was somewhat tedious. Now, the new ``replace()`` method makes
it possible to create a clone with a few altered parameters.
Here's an example that alters the :func:`statistics.mean` function to
prevent the *data* parameter from being used as a keyword argument::
>>> from statistics import mean
>>> mean(data=[10, 20, 90])
40
>>> mean.__code__ = mean.__code__.replace(co_posonlyargcount=1)
>>> mean(data=[10, 20, 90])
Traceback (most recent call last):
...
TypeError: mean() got some positional-only arguments passed as keyword arguments: 'data'
(Contributed by Victor Stinner in :issue:`37032`.)
* For integers, the three-argument form of the :func:`pow` function now
permits the exponent to be negative in the case where the base is
relatively prime to the modulus. It then computes a modular inverse to
the base when the exponent is ``-1``, and a suitable power of that
inverse for other negative exponents. For example, to compute the
`modular multiplicative inverse
<https://en.wikipedia.org/wiki/Modular_multiplicative_inverse>`_ of 38
modulo 137, write::
>>> pow(38, -1, 137)
119
>>> 119 * 38 % 137
1
Modular inverses arise in the solution of `linear Diophantine
equations <https://en.wikipedia.org/wiki/Diophantine_equation>`_.
For example, to find integer solutions for ``4258𝑥 + 147𝑦 = 369``,
first rewrite as ``4258𝑥 ≡ 369 (mod 147)`` then solve:
>>> x = 369 * pow(4258, -1, 147) % 147
>>> y = (4258 * x - 369) // -147
>>> 4258 * x + 147 * y
369
(Contributed by Mark Dickinson in :issue:`36027`.)
* Dict comprehensions have been synced-up with dict literals so that the
key is computed first and the value second::
>>> # Dict comprehension
>>> cast = {input('role? '): input('actor? ') for i in range(2)}
role? King Arthur
actor? Chapman
role? Black Knight
actor? Cleese
>>> # Dict literal
>>> cast = {input('role? '): input('actor? ')}
role? Sir Robin
actor? Eric Idle
The guaranteed execution order is helpful with assignment expressions
because variables assigned in the key expression will be available in
the value expression::
>>> names = ['Martin von Löwis', 'Łukasz Langa', 'Walter Dörwald']
>>> {(n := normalize('NFC', name)).casefold() : n for name in names}
{'martin von löwis': 'Martin von Löwis',
'łukasz langa': 'Łukasz Langa',
'walter dörwald': 'Walter Dörwald'}
(Contributed by Jörn Heissler in :issue:`35224`.)
* The :meth:`object.__reduce__` method can now return a tuple from two to
six elements long. Formerly, five was the limit. The new, optional sixth
element is a callable with a ``(obj, state)`` signature. This allows the
direct control over the state-updating behavior of a specific object. If
not *None*, this callable will have priority over the object's
:meth:`~__setstate__` method.
(Contributed by Pierre Glaser and Olivier Grisel in :issue:`35900`.)
New Modules
===========
* The new :mod:`importlib.metadata` module provides (provisional) support for
reading metadata from third-party packages. For example, it can extract an
installed package's version number, list of entry points, and more::
>>> # Note following example requires that the popular "requests"
>>> # package has been installed.
>>>
>>> from importlib.metadata import version, requires, files
>>> version('requests')
'2.22.0'
>>> list(requires('requests'))
['chardet (<3.1.0,>=3.0.2)']
>>> list(files('requests'))[:5]
[PackagePath('requests-2.22.0.dist-info/INSTALLER'),
PackagePath('requests-2.22.0.dist-info/LICENSE'),
PackagePath('requests-2.22.0.dist-info/METADATA'),
PackagePath('requests-2.22.0.dist-info/RECORD'),
PackagePath('requests-2.22.0.dist-info/WHEEL')]
(Contributed by Barry Warsaw and Jason R. Coombs in :issue:`34632`.)
Improved Modules
================
ast
---
AST nodes now have ``end_lineno`` and ``end_col_offset`` attributes,
which give the precise location of the end of the node. (This only
applies to nodes that have ``lineno`` and ``col_offset`` attributes.)
New function :func:`ast.get_source_segment` returns the source code
for a specific AST node.
(Contributed by Ivan Levkivskyi in :issue:`33416`.)
The :func:`ast.parse` function has some new flags:
* ``type_comments=True`` causes it to return the text of :pep:`484` and
:pep:`526` type comments associated with certain AST nodes;
* ``mode='func_type'`` can be used to parse :pep:`484` "signature type
comments" (returned for function definition AST nodes);
* ``feature_version=(3, N)`` allows specifying an earlier Python 3
version. For example, ``feature_version=(3, 4)`` will treat
:keyword:`async` and :keyword:`await` as non-reserved words.
(Contributed by Guido van Rossum in :issue:`35766`.)
asyncio
-------
:func:`asyncio.run` has graduated from the provisional to stable API. This
function can be used to execute a :term:`coroutine` and return the result while
automatically managing the event loop. For example::
import asyncio
async def main():
await asyncio.sleep(0)
return 42
asyncio.run(main())
This is *roughly* equivalent to::
import asyncio
async def main():
await asyncio.sleep(0)
return 42
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
loop.run_until_complete(main())
finally:
asyncio.set_event_loop(None)
loop.close()
The actual implementation is significantly more complex. Thus,
:func:`asyncio.run` should be the preferred way of running asyncio programs.
(Contributed by Yury Selivanov in :issue:`32314`.)
Running ``python -m asyncio`` launches a natively async REPL. This allows rapid
experimentation with code that has a top-level :keyword:`await`. There is no
longer a need to directly call ``asyncio.run()`` which would spawn a new event
loop on every invocation:
.. code-block:: none
$ python -m asyncio
asyncio REPL 3.8.0
Use "await" directly instead of "asyncio.run()".
Type "help", "copyright", "credits" or "license" for more information.
>>> import asyncio
>>> await asyncio.sleep(10, result='hello')
hello
(Contributed by Yury Selivanov in :issue:`37028`.)
The exception :class:`asyncio.CancelledError` now inherits from
:class:`BaseException` rather than :class:`Exception` and no longer inherits
from :class:`concurrent.futures.CancelledError`.
(Contributed by Yury Selivanov in :issue:`32528`.)
On Windows, the default event loop is now :class:`~asyncio.ProactorEventLoop`.
(Contributed by Victor Stinner in :issue:`34687`.)
:class:`~asyncio.ProactorEventLoop` now also supports UDP.
(Contributed by Adam Meily and Andrew Svetlov in :issue:`29883`.)
:class:`~asyncio.ProactorEventLoop` can now be interrupted by
:exc:`KeyboardInterrupt` ("CTRL+C").
(Contributed by Vladimir Matveev in :issue:`23057`.)
Added :meth:`asyncio.Task.get_coro` for getting the wrapped coroutine
within an :class:`asyncio.Task`.
(Contributed by Alex Grönholm in :issue:`36999`.)
Asyncio tasks can now be named, either by passing the ``name`` keyword
argument to :func:`asyncio.create_task` or
the :meth:`~asyncio.loop.create_task` event loop method, or by
calling the :meth:`~asyncio.Task.set_name` method on the task object. The
task name is visible in the ``repr()`` output of :class:`asyncio.Task` and
can also be retrieved using the :meth:`~asyncio.Task.get_name` method.
(Contributed by Alex Grönholm in :issue:`34270`.)
Added support for
`Happy Eyeballs <https://en.wikipedia.org/wiki/Happy_Eyeballs>`_ to
:func:`asyncio.loop.create_connection`. To specify the behavior, two new
parameters have been added: *happy_eyeballs_delay* and *interleave*. The Happy
Eyeballs algorithm improves responsiveness in applications that support IPv4
and IPv6 by attempting to simultaneously connect using both.
(Contributed by twisteroid ambassador in :issue:`33530`.)
builtins
--------
The :func:`compile` built-in has been improved to accept the
``ast.PyCF_ALLOW_TOP_LEVEL_AWAIT`` flag. With this new flag passed,
:func:`compile` will allow top-level ``await``, ``async for`` and ``async with``
constructs that are usually considered invalid syntax. Asynchronous code object
marked with the ``CO_COROUTINE`` flag may then be returned.
(Contributed by Matthias Bussonnier in :issue:`34616`)
collections
-----------
The :meth:`~collections.somenamedtuple._asdict` method for
:func:`collections.namedtuple` now returns a :class:`dict` instead of a
:class:`collections.OrderedDict`. This works because regular dicts have
guaranteed ordering since Python 3.7. If the extra features of
:class:`OrderedDict` are required, the suggested remediation is to cast the
result to the desired type: ``OrderedDict(nt._asdict())``.
(Contributed by Raymond Hettinger in :issue:`35864`.)
cProfile
--------
The :class:`cProfile.Profile <profile.Profile>` class can now be used as a context manager.
Profile a block of code by running::
import cProfile
with cProfile.Profile() as profiler:
# code to be profiled
...
(Contributed by Scott Sanderson in :issue:`29235`.)
csv
---
The :class:`csv.DictReader` now returns instances of :class:`dict` instead of
a :class:`collections.OrderedDict`. The tool is now faster and uses less
memory while still preserving the field order.
(Contributed by Michael Selik in :issue:`34003`.)
curses
-------
Added a new variable holding structured version information for the
underlying ncurses library: :data:`~curses.ncurses_version`.
(Contributed by Serhiy Storchaka in :issue:`31680`.)
ctypes
------
On Windows, :class:`~ctypes.CDLL` and subclasses now accept a *winmode* parameter
to specify flags for the underlying ``LoadLibraryEx`` call. The default flags are
set to only load DLL dependencies from trusted locations, including the path
where the DLL is stored (if a full or partial path is used to load the initial
DLL) and paths added by :func:`~os.add_dll_directory`.
(Contributed by Steve Dower in :issue:`36085`.)
datetime
--------
Added new alternate constructors :meth:`datetime.date.fromisocalendar` and
:meth:`datetime.datetime.fromisocalendar`, which construct :class:`~datetime.date` and
:class:`~datetime.datetime` objects respectively from ISO year, week number, and weekday;
these are the inverse of each class's ``isocalendar`` method.
(Contributed by Paul Ganssle in :issue:`36004`.)
functools
---------
:func:`functools.lru_cache` can now be used as a straight decorator rather
than as a function returning a decorator. So both of these are now supported::
@lru_cache
def f(x):
...
@lru_cache(maxsize=256)
def f(x):
...
(Contributed by Raymond Hettinger in :issue:`36772`.)
Added a new :func:`functools.cached_property` decorator, for computed properties
cached for the life of the instance. ::
import functools
import statistics
class Dataset:
def __init__(self, sequence_of_numbers):
self.data = sequence_of_numbers
@functools.cached_property
def variance(self):
return statistics.variance(self.data)
(Contributed by Carl Meyer in :issue:`21145`)
Added a new :func:`functools.singledispatchmethod` decorator that converts
methods into :term:`generic functions <generic function>` using
:term:`single dispatch`::
from functools import singledispatchmethod
from contextlib import suppress
class TaskManager:
def __init__(self, tasks):
self.tasks = list(tasks)
@singledispatchmethod
def discard(self, value):
with suppress(ValueError):
self.tasks.remove(value)
@discard.register(list)
def _(self, tasks):
targets = set(tasks)
self.tasks = [x for x in self.tasks if x not in targets]
(Contributed by Ethan Smith in :issue:`32380`)
gc
--
:func:`~gc.get_objects` can now receive an optional *generation* parameter
indicating a generation to get objects from.
(Contributed by Pablo Galindo in :issue:`36016`.)
gettext
-------
Added :func:`~gettext.pgettext` and its variants.
(Contributed by Franz Glasner, Éric Araujo, and Cheryl Sabella in :issue:`2504`.)
gzip
----
Added the *mtime* parameter to :func:`gzip.compress` for reproducible output.
(Contributed by Guo Ci Teo in :issue:`34898`.)
A :exc:`~gzip.BadGzipFile` exception is now raised instead of :exc:`OSError`
for certain types of invalid or corrupt gzip files.
(Contributed by Filip Gruszczyński, Michele Orrù, and Zackery Spytz in
:issue:`6584`.)
IDLE and idlelib
----------------
Output over N lines (50 by default) is squeezed down to a button.
N can be changed in the PyShell section of the General page of the
Settings dialog. Fewer, but possibly extra long, lines can be squeezed by
right clicking on the output. Squeezed output can be expanded in place
by double-clicking the button or into the clipboard or a separate window
by right-clicking the button. (Contributed by Tal Einat in :issue:`1529353`.)
Add "Run Customized" to the Run menu to run a module with customized
settings. Any command line arguments entered are added to sys.argv.
They also re-appear in the box for the next customized run. One can also
suppress the normal Shell main module restart. (Contributed by Cheryl
Sabella, Terry Jan Reedy, and others in :issue:`5680` and :issue:`37627`.)
Added optional line numbers for IDLE editor windows. Windows
open without line numbers unless set otherwise in the General
tab of the configuration dialog. Line numbers for an existing
window are shown and hidden in the Options menu.
(Contributed by Tal Einat and Saimadhav Heblikar in :issue:`17535`.)
OS native encoding is now used for converting between Python strings and Tcl
objects. This allows IDLE to work with emoji and other non-BMP characters.
These characters can be displayed or copied and pasted to or from the
clipboard. Converting strings from Tcl to Python and back now never fails.
(Many people worked on this for eight years but the problem was finally
solved by Serhiy Storchaka in :issue:`13153`.)
New in 3.8.1:
Add option to toggle cursor blink off. (Contributed by Zackery Spytz
in :issue:`4603`.)
Escape key now closes IDLE completion windows. (Contributed by Johnny
Najera in :issue:`38944`.)
The changes above have been backported to 3.7 maintenance releases.
Add keywords to module name completion list. (Contributed by Terry J.
Reedy in :issue:`37765`.)
inspect
-------
The :func:`inspect.getdoc` function can now find docstrings for ``__slots__``
if that attribute is a :class:`dict` where the values are docstrings.
This provides documentation options similar to what we already have
for :func:`property`, :func:`classmethod`, and :func:`staticmethod`::
class AudioClip:
__slots__ = {'bit_rate': 'expressed in kilohertz to one decimal place',
'duration': 'in seconds, rounded up to an integer'}
def __init__(self, bit_rate, duration):
self.bit_rate = round(bit_rate / 1000.0, 1)
self.duration = ceil(duration)
(Contributed by Raymond Hettinger in :issue:`36326`.)
io
--
In development mode (:option:`-X` ``env``) and in :ref:`debug build <debug-build>`, the
:class:`io.IOBase` finalizer now logs the exception if the ``close()`` method
fails. The exception is ignored silently by default in release build.
(Contributed by Victor Stinner in :issue:`18748`.)
itertools
---------
The :func:`itertools.accumulate` function added an option *initial* keyword
argument to specify an initial value::
>>> from itertools import accumulate
>>> list(accumulate([10, 5, 30, 15], initial=1000))
[1000, 1010, 1015, 1045, 1060]
(Contributed by Lisa Roach in :issue:`34659`.)
json.tool
---------
Add option ``--json-lines`` to parse every input line as a separate JSON object.
(Contributed by Weipeng Hong in :issue:`31553`.)
logging
-------
Added a *force* keyword argument to :func:`logging.basicConfig`
When set to true, any existing handlers attached
to the root logger are removed and closed before carrying out the
configuration specified by the other arguments.
This solves a long-standing problem. Once a logger or *basicConfig()* had
been called, subsequent calls to *basicConfig()* were silently ignored.
This made it difficult to update, experiment with, or teach the various
logging configuration options using the interactive prompt or a Jupyter
notebook.
(Suggested by Raymond Hettinger, implemented by Donghee Na, and
reviewed by Vinay Sajip in :issue:`33897`.)
math
----
Added new function :func:`math.dist` for computing Euclidean distance
between two points. (Contributed by Raymond Hettinger in :issue:`33089`.)
Expanded the :func:`math.hypot` function to handle multiple dimensions.
Formerly, it only supported the 2-D case.
(Contributed by Raymond Hettinger in :issue:`33089`.)
Added new function, :func:`math.prod`, as analogous function to :func:`sum`
that returns the product of a 'start' value (default: 1) times an iterable of
numbers::
>>> prior = 0.8
>>> likelihoods = [0.625, 0.84, 0.30]
>>> math.prod(likelihoods, start=prior)
0.126
(Contributed by Pablo Galindo in :issue:`35606`.)
Added two new combinatoric functions :func:`math.perm` and :func:`math.comb`::
>>> math.perm(10, 3) # Permutations of 10 things taken 3 at a time
720
>>> math.comb(10, 3) # Combinations of 10 things taken 3 at a time
120
(Contributed by Yash Aggarwal, Keller Fuchs, Serhiy Storchaka, and Raymond
Hettinger in :issue:`37128`, :issue:`37178`, and :issue:`35431`.)
Added a new function :func:`math.isqrt` for computing accurate integer square
roots without conversion to floating point. The new function supports
arbitrarily large integers. It is faster than ``floor(sqrt(n))`` but slower
than :func:`math.sqrt`::
>>> r = 650320427
>>> s = r ** 2
>>> isqrt(s - 1) # correct
650320426
>>> floor(sqrt(s - 1)) # incorrect
650320427
(Contributed by Mark Dickinson in :issue:`36887`.)
The function :func:`math.factorial` no longer accepts arguments that are not
int-like. (Contributed by Pablo Galindo in :issue:`33083`.)