Repository navigation
Expand file tree
/
Copy path3.14.rst
More file actions
3506 lines (2564 loc) · 130 KB
/
Copy path3.14.rst
File metadata and controls
3506 lines (2564 loc) · 130 KB
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.14
****************************
:Editors: Adam Turner and Hugo van Kemenade
.. 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 issue number as a comment:
XXX Describe the transmogrify() function added to the socket
module.
(Contributed by P.Y. Developer in :gh:`12345`.)
This saves the maintainer the effort of going through the VCS log
when researching a change.
This article explains the new features in Python 3.14, compared to 3.13.
Python 3.14 was released on 7 October 2025.
For full details, see the :ref:`changelog <changelog>`.
.. seealso::
:pep:`745` -- Python 3.14 release schedule
Summary -- Release highlights
=============================
.. This section singles out the most important changes in Python 3.14.
Brevity is key.
Python 3.14 is a stable release of the Python programming
language, with a mix of changes to the language, the implementation,
and the standard library.
The biggest changes include :ref:`template string literals
<whatsnew314-template-string-literals>`,
:ref:`deferred evaluation of annotations <whatsnew314-deferred-annotations>`,
and support for :ref:`subinterpreters <whatsnew314-multiple-interpreters>` in
the standard library.
The library changes include significantly improved capabilities for
:ref:`introspection in asyncio <whatsnew314-asyncio-introspection>`,
:ref:`support for Zstandard <whatsnew314-zstandard>` via a new
:mod:`compression.zstd` module, syntax highlighting in the REPL,
as well as the usual deprecations and removals,
and improvements in user-friendliness and correctness.
This article doesn't attempt to provide a complete specification
of all new features, but instead gives a convenient overview.
For full details refer to the documentation,
such as the :ref:`Library Reference <library-index>`
and :ref:`Language Reference <reference-index>`.
To understand the complete implementation and design rationale for a change,
refer to the PEP for a particular new feature;
but note that PEPs usually are not kept up-to-date
once a feature has been fully implemented.
See `Porting to Python 3.14`_ for guidance on upgrading from
earlier versions of Python.
--------------
.. PEP-sized items next.
Interpreter improvements:
* :pep:`649` and :pep:`749`: :ref:`Deferred evaluation of annotations
<whatsnew314-deferred-annotations>`
* :pep:`734`: :ref:`Multiple interpreters in the standard library
<whatsnew314-multiple-interpreters>`
* :pep:`750`: :ref:`Template strings <whatsnew314-template-string-literals>`
* :pep:`758`: :ref:`Allow except and except* expressions without brackets
<whatsnew314-bracketless-except>`
* :pep:`765`: :ref:`Control flow in finally blocks
<whatsnew314-finally-syntaxwarning>`
* :pep:`768`: :ref:`Safe external debugger interface for CPython
<whatsnew314-remote-debugging>`
* :ref:`A new type of interpreter <whatsnew314-tail-call-interpreter>`
* :ref:`Free-threaded mode improvements <whatsnew314-free-threaded-cpython>`
* :ref:`Improved error messages <whatsnew314-improved-error-messages>`
* :ref:`Incremental garbage collection <whatsnew314-incremental-gc>`
Significant improvements in the standard library:
* :pep:`784`: :ref:`Zstandard support in the standard library
<whatsnew314-zstandard>`
* :ref:`whatsnew314-asyncio-introspection`
* :ref:`whatsnew314-concurrent-warnings-control`
* :ref:`Syntax highlighting in the default interactive shell
<whatsnew314-pyrepl-highlighting>`, and color output in several
standard library CLIs
C API improvements:
* :pep:`741`: :ref:`Python configuration C API <whatsnew314-capi-config>`
Platform support:
* :pep:`776`: Emscripten is now an :ref:`officially supported platform
<whatsnew314-build-changes>`, at :pep:`tier 3 <11#tier-3>`.
Release changes:
* :pep:`779`: :ref:`Free-threaded Python is officially supported
<whatsnew314-free-threaded-now-supported>`
* :pep:`761`: :ref:`PGP signatures have been discontinued for official releases
<whatsnew314-no-more-pgp>`
* :ref:`Windows and macOS binary releases now support the experimental
just-in-time compiler <whatsnew314-jit-compiler>`
* :ref:`Binary releases for Android are now provided <whatsnew314-build-changes>`
New features
============
.. _whatsnew314-deferred-annotations:
:pep:`649` & :pep:`749`: Deferred evaluation of annotations
------------------------------------------------------------
The :term:`annotations <annotation>` on functions, classes, and modules are no
longer evaluated eagerly. Instead, annotations are stored in special-purpose
:term:`annotate functions <annotate function>` and evaluated only when
necessary (except if ``from __future__ import annotations`` is used).
This change is designed to improve performance and usability of annotations
in Python in most circumstances. The runtime cost for defining annotations is
minimized, but it remains possible to introspect annotations at runtime.
It is no longer necessary to enclose annotations in strings if they
contain forward references.
The new :mod:`annotationlib` module provides tools for inspecting deferred
annotations. Annotations may be evaluated in the :attr:`~annotationlib.Format.VALUE`
format (which evaluates annotations to runtime values, similar to the behavior in
earlier Python versions), the :attr:`~annotationlib.Format.FORWARDREF` format
(which replaces undefined names with special markers), and the
:attr:`~annotationlib.Format.STRING` format (which returns annotations as strings).
This example shows how these formats behave:
.. doctest::
>>> from annotationlib import get_annotations, Format
>>> def func(arg: Undefined):
... pass
>>> get_annotations(func, format=Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'Undefined' is not defined
>>> get_annotations(func, format=Format.FORWARDREF)
{'arg': ForwardRef('Undefined', owner=<function func at 0x...>)}
>>> get_annotations(func, format=Format.STRING)
{'arg': 'Undefined'}
The :ref:`porting <whatsnew314-porting-annotations>` section contains guidance
on changes that may be needed due to these changes, though in the majority of
cases, code will continue working as-is.
(Contributed by Jelle Zijlstra in :pep:`749` and :gh:`119180`;
:pep:`649` was written by Larry Hastings.)
.. seealso::
:pep:`649`
Deferred Evaluation Of Annotations Using Descriptors
:pep:`749`
Implementing PEP 649
.. _whatsnew314-multiple-interpreters:
:pep:`734`: Multiple interpreters in the standard library
---------------------------------------------------------
The CPython runtime supports running multiple copies of Python in the
same process simultaneously and has done so for over 20 years.
Each of these separate copies is called an 'interpreter'.
However, the feature had been available only through
the :ref:`C-API <sub-interpreter-support>`.
That limitation is removed in Python 3.14,
with the new :mod:`concurrent.interpreters` module.
There are at least two notable reasons why using multiple interpreters
has significant benefits:
* they support a new (to Python), human-friendly concurrency model
* true multi-core parallelism
For some use cases, concurrency in software improves efficiency and
can simplify design, at a high level.
At the same time, implementing and maintaining all but the simplest concurrency
is often a struggle for the human brain.
That especially applies to plain threads (for example, :mod:`threading`),
where all memory is shared between all threads.
With multiple isolated interpreters, you can take advantage of a class
of concurrency models, like Communicating Sequential Processes (CSP)
or the actor model, that have found
success in other programming languages, like Smalltalk, Erlang,
Haskell, and Go. Think of multiple interpreters as threads
but with opt-in sharing.
Regarding multi-core parallelism: as of Python 3.12, interpreters
are now sufficiently isolated from one another to be used in parallel
(see :pep:`684`). This unlocks a variety of CPU-intensive use cases
for Python that were limited by the :term:`GIL`.
Using multiple interpreters is similar in many ways to
:mod:`multiprocessing`, in that they both provide isolated logical
"processes" that can run in parallel, with no sharing by default.
However, when using multiple interpreters, an application will use
fewer system resources and will operate more efficiently (since it
stays within the same process). Think of multiple interpreters as
having the isolation of processes with the efficiency of threads.
.. XXX Add an example or two.
.. XXX Link to the not-yet-added HOWTO doc.
While the feature has been around for decades, multiple interpreters
have not been used widely, due to low awareness and the lack of a
standard library module. Consequently, they currently have several
notable limitations, which are expected to improve significantly now
that the feature is going mainstream.
Current limitations:
* starting each interpreter has not been optimized yet
* each interpreter uses more memory than necessary
(work continues on extensive internal sharing between interpreters)
* there aren't many options *yet* for truly sharing objects or other
data between interpreters (other than :type:`memoryview`)
* many third-party extension modules on PyPI are not yet compatible
with multiple interpreters
(all standard library extension modules *are* compatible)
* the approach to writing applications that use multiple isolated
interpreters is mostly unfamiliar to Python users, for now
The impact of these limitations will depend on future CPython
improvements, how interpreters are used, and what the community solves
through PyPI packages. Depending on the use case, the limitations may
not have much impact, so try it out!
Furthermore, future CPython releases will reduce or eliminate overhead
and provide utilities that are less appropriate on PyPI. In the
meantime, most of the limitations can also be addressed through
extension modules, meaning PyPI packages can fill any gap for 3.14, and
even back to 3.12 where interpreters were finally properly isolated and
stopped sharing the :term:`GIL`. Likewise, libraries on PyPI are expected
to emerge for high-level abstractions on top of interpreters.
Regarding extension modules, work is in progress to update some PyPI
projects, as well as tools like Cython, pybind11, nanobind, and PyO3.
The steps for isolating an extension module are found at
:ref:`isolating-extensions-howto`.
Isolating a module has a lot of overlap with what is required to support
:ref:`free-threading <whatsnew314-free-threaded-cpython>`, so the ongoing
work in the community in that area will help accelerate support
for multiple interpreters.
Also added in 3.14: :ref:`concurrent.futures.InterpreterPoolExecutor
<whatsnew314-concurrent-futures-interp-pool>`.
(Contributed by Eric Snow in :gh:`134939`.)
.. seealso:: :pep:`734`
.. _whatsnew314-template-string-literals:
:pep:`750`: Template string literals
------------------------------------
Template strings are a new mechanism for custom string processing.
They share the familiar syntax of f-strings but, unlike f-strings,
return an object representing the static and interpolated parts of
the string, instead of a simple :class:`str`.
To write a t-string, use a ``'t'`` prefix instead of an ``'f'``:
.. doctest::
>>> variety = 'Stilton'
>>> template = t'Try some {variety} cheese!'
>>> type(template)
<class 'string.templatelib.Template'>
:class:`~string.templatelib.Template` objects provide access to the static
and interpolated (in curly braces) parts of a string *before* they are combined.
Iterate over :class:`!Template` instances to access their parts in order:
.. testsetup::
variety = 'Stilton'
template = t'Try some {variety} cheese!'
.. doctest::
>>> list(template)
['Try some ', Interpolation('Stilton', 'variety', None, ''), ' cheese!']
It's easy to write (or call) code to process :class:`!Template` instances.
For example, here's a function that renders static parts lowercase and
:class:`~string.templatelib.Interpolation` instances uppercase:
.. code-block:: python
from string.templatelib import Interpolation
def lower_upper(template):
"""Render static parts lowercase and interpolations uppercase."""
parts = []
for part in template:
if isinstance(part, Interpolation):
parts.append(str(part.value).upper())
else:
parts.append(part.lower())
return ''.join(parts)
name = 'Wenslydale'
template = t'Mister {name}'
assert lower_upper(template) == 'mister WENSLYDALE'
Because :class:`!Template` instances distinguish between static strings and
interpolations at runtime, they can be useful for sanitising user input.
Writing a :func:`!html` function that escapes user input in HTML is an exercise
left to the reader!
Template processing code can provide improved flexibility.
For instance, a more advanced :func:`!html` function could accept
a :class:`!dict` of HTML attributes directly in the template:
.. code-block:: python
attributes = {'src': 'limburger.jpg', 'alt': 'lovely cheese'}
template = t'<img {attributes}>'
assert html(template) == '<img src="limburger.jpg" alt="lovely cheese" />'
Of course, template processing code does not need to return a string-like result.
An even *more* advanced :func:`!html` could return a custom type representing
a DOM-like structure.
With t-strings in place, developers can write systems that sanitise SQL,
make safe shell operations, improve logging, tackle modern ideas in web
development (HTML, CSS, and so on), and implement lightweight custom business DSLs.
(Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono,
Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran,
and Pablo Galindo Salgado in :gh:`132661`.)
.. seealso:: :pep:`750`.
.. _whatsnew314-remote-debugging:
:pep:`768`: Safe external debugger interface
--------------------------------------------
Python 3.14 introduces a zero-overhead debugging interface that allows
debuggers and profilers to safely attach to running Python processes
without stopping or restarting them.
This is a significant enhancement to Python's debugging capabilities,
meaning that unsafe alternatives are no longer required.
The new interface provides safe execution points for attaching debugger code
without modifying the interpreter's normal execution path
or adding any overhead at runtime.
Due to this, tools can now inspect and interact with Python applications
in real-time, which is a crucial capability for high-availability systems
and production environments.
For convenience, this interface is implemented in the :func:`sys.remote_exec`
function. For example:
.. code-block:: python
import sys
from tempfile import NamedTemporaryFile
with NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
script_path = f.name
f.write(f'import my_debugger; my_debugger.connect({os.getpid()})')
# Execute in process with PID 1234
print('Behold! An offering:')
sys.remote_exec(1234, script_path)
This function allows sending Python code to be executed in a target process
at the next safe execution point.
However, tool authors can also implement the protocol directly as described
in the PEP, which details the underlying mechanisms used to safely attach to
running processes.
The debugging interface has been carefully designed with security in mind
and includes several mechanisms to control access:
* A :envvar:`PYTHON_DISABLE_REMOTE_DEBUG` environment variable.
* A :option:`-X disable-remote-debug` command-line option.
* A :option:`--without-remote-debug` configure flag to completely disable
the feature at build time.
(Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic
in :gh:`131591`.)
.. seealso:: :pep:`768`.
.. _whatsnew314-tail-call-interpreter:
A new type of interpreter
-------------------------
A new type of interpreter has been added to CPython.
It uses tail calls between small C functions that implement individual
Python opcodes, rather than one large C ``case`` statement.
For certain newer compilers, this interpreter provides
significantly better performance. Preliminary benchmarks suggest a geometric
mean of 3-5% faster on the standard ``pyperformance`` benchmark suite,
depending on platform and architecture.
The baseline is Python 3.14 built with Clang 19, without this new interpreter.
This interpreter currently only works with Clang 19 and newer
on x86-64 and AArch64 architectures.
However, a future release of GCC is expected to support this as well.
This feature is opt-in for now. Enabling profile-guided optimization is highly
recommended when using the new interpreter as it is the only configuration
that has been tested and validated for improved performance.
For further information, see :option:`--with-tail-call-interp`.
.. note::
This is not to be confused with `tail call optimization`__ of Python
functions, which is currently not implemented in CPython.
This new interpreter type is an internal implementation detail of the CPython
interpreter. It doesn't change the visible behavior of Python programs at
all. It can improve their performance, but doesn't change anything else.
__ https://en.wikipedia.org/wiki/Tail_call
(Contributed by Ken Jin in :gh:`128563`, with ideas on how to implement this
in CPython by Mark Shannon, Garrett Gu, Haoran Xu, and Josh Haberman.)
.. _whatsnew314-free-threaded-cpython:
Free-threaded mode improvements
-------------------------------
CPython's free-threaded mode (:pep:`703`), initially added in 3.13,
has been significantly improved in Python 3.14.
The implementation described in PEP 703 has been finished, including C API
changes, and temporary workarounds in the interpreter were replaced with
more permanent solutions.
The specializing adaptive interpreter (:pep:`659`) is now enabled
in free-threaded mode, which along with many other optimizations
greatly improves its performance.
The performance penalty on single-threaded code in free-threaded mode
is now roughly 5-10%, depending on the platform and C compiler used.
From Python 3.14, when compiling extension modules for the free-threaded build of
CPython on Windows, the preprocessor variable ``Py_GIL_DISABLED`` now needs to
be specified by the build backend, as it will no longer be determined
automatically by the C compiler. For a running interpreter, the setting that
was used at compile time can be found using :func:`sysconfig.get_config_var`.
The new :option:`-X context_aware_warnings <-X>` flag controls if
:ref:`concurrent safe warnings control <whatsnew314-concurrent-warnings-control>`
is enabled. The flag defaults to true for the free-threaded build
and false for the GIL-enabled build.
A new :data:`~sys.flags.thread_inherit_context` flag has been added,
which if enabled means that threads created with :class:`threading.Thread`
start with a copy of the :class:`~contextvars.Context()` of the caller of
:meth:`~threading.Thread.start`. Most significantly, this makes the warning
filtering context established by :class:`~warnings.catch_warnings` be
"inherited" by threads (or asyncio tasks) started within that context. It also
affects other modules that use context variables, such as the :mod:`decimal`
context manager.
This flag defaults to true for the free-threaded build and false for
the GIL-enabled build.
(Contributed by Sam Gross, Matt Page, Neil Schemenauer, Thomas Wouters,
Donghee Na, Kirill Podoprigora, Ken Jin, Itamar Oren, Brett Simmers,
Dino Viehland, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, Kumar Aditya,
Edgar Margffoy, and many others.
Some of these contributors are employed by Meta, which has continued to provide
significant engineering resources to support this project.)
.. _whatsnew314-improved-error-messages:
Improved error messages
-----------------------
* The interpreter now provides helpful suggestions when it detects typos in Python
keywords. When a word that closely resembles a Python keyword is encountered,
the interpreter will suggest the correct keyword in the error message. This
feature helps programmers quickly identify and fix common typing mistakes. For
example:
.. code-block:: pycon
>>> whille True:
... pass
Traceback (most recent call last):
File "<stdin>", line 1
whille True:
^^^^^^
SyntaxError: invalid syntax. Did you mean 'while'?
While the feature focuses on the most common cases, some variations of
misspellings may still result in regular syntax errors.
(Contributed by Pablo Galindo in :gh:`132449`.)
* :keyword:`elif` statements that follow an :keyword:`else` block now have
a specific error message.
(Contributed by Steele Farnsworth in :gh:`129902`.)
.. code-block:: pycon
>>> if who == "me":
... print("It's me!")
... else:
... print("It's not me!")
... elif who is None:
... print("Who is it?")
File "<stdin>", line 5
elif who is None:
^^^^
SyntaxError: 'elif' block follows an 'else' block
* If a statement is passed to the :ref:`if_expr` after :keyword:`else`,
or one of :keyword:`pass`, :keyword:`break`, or :keyword:`continue`
is passed before :keyword:`if`, then the
error message highlights where the :token:`~python-grammar:expression` is
required. (Contributed by Sergey Miryanov in :gh:`129515`.)
.. code-block:: pycon
>>> x = 1 if True else pass
Traceback (most recent call last):
File "<string>", line 1
x = 1 if True else pass
^^^^
SyntaxError: expected expression after 'else', but statement is given
>>> x = continue if True else break
Traceback (most recent call last):
File "<string>", line 1
x = continue if True else break
^^^^^^^^
SyntaxError: expected expression before 'if', but statement is given
* When incorrectly closed strings are detected, the error message suggests
that the string may be intended to be part of the string.
(Contributed by Pablo Galindo in :gh:`88535`.)
.. code-block:: pycon
>>> "The interesting object "The important object" is very important"
Traceback (most recent call last):
SyntaxError: invalid syntax. Is this intended to be part of the string?
* When strings have incompatible prefixes, the error now shows
which prefixes are incompatible.
(Contributed by Nikita Sobolev in :gh:`133197`.)
.. code-block:: pycon
>>> ub'abc'
File "<python-input-0>", line 1
ub'abc'
^^
SyntaxError: 'u' and 'b' prefixes are incompatible
* Improved error messages when using ``as`` with incompatible targets in:
- Imports: ``import ... as ...``
- From imports: ``from ... import ... as ...``
- Except handlers: ``except ... as ...``
- Pattern-match cases: ``case ... as ...``
(Contributed by Nikita Sobolev in :gh:`123539`, :gh:`123562`, and :gh:`123440`.)
* Improved error message when trying to add an instance of an unhashable type to
a :class:`dict` or :class:`set`.
(Contributed by CF Bolz-Tereick and Victor Stinner in :gh:`132828`.)
.. code-block:: pycon
>>> s = set()
>>> s.add({'pages': 12, 'grade': 'A'})
Traceback (most recent call last):
File "<python-input-1>", line 1, in <module>
s.add({'pages': 12, 'grade': 'A'})
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: cannot use 'dict' as a set element (unhashable type: 'dict')
>>> d = {}
>>> l = [1, 2, 3]
>>> d[l] = 12
Traceback (most recent call last):
File "<python-input-4>", line 1, in <module>
d[l] = 12
~^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
* Improved error message when an object supporting the synchronous
context manager protocol is entered using :keyword:`async with`
instead of :keyword:`with`,
and vice versa for the asynchronous context manager protocol.
(Contributed by Bénédikt Tran in :gh:`128398`.)
.. _whatsnew314-zstandard:
:pep:`784`: Zstandard support in the standard library
-----------------------------------------------------
The new :mod:`compression` package contains modules :mod:`!compression.lzma`,
:mod:`!compression.bz2`, :mod:`!compression.gzip` and :mod:`!compression.zlib`
which re-export the :mod:`lzma`, :mod:`bz2`, :mod:`gzip` and :mod:`zlib`
modules respectively. The new import names under :mod:`!compression` are the
preferred names for importing these compression modules from Python 3.14. However,
the existing modules names have not been deprecated. Any deprecation or removal
of the existing compression modules will occur no sooner than five years after
the release of 3.14.
The new :mod:`compression.zstd` module provides compression and decompression
APIs for the Zstandard format via bindings to `Meta's zstd library
<https://facebook.github.io/zstd/>`__. Zstandard is a widely adopted, highly
efficient, and fast compression format. In addition to the APIs introduced in
:mod:`!compression.zstd`, support for reading and writing Zstandard compressed
archives has been added to the :mod:`tarfile`, :mod:`zipfile`, and
:mod:`shutil` modules.
Here's an example of using the new module to compress some data:
.. code-block:: python
from compression import zstd
import math
data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of {ratio}")
As can be seen, the API is similar to the APIs of the :mod:`!lzma` and
:mod:`!bz2` modules.
(Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun,
Victor Stinner, and Rogdham in :gh:`132983`.)
.. seealso:: :pep:`784`.
.. _whatsnew314-asyncio-introspection:
Asyncio introspection capabilities
----------------------------------
Added a new command-line interface to inspect running Python processes
using asynchronous tasks, available via ``python -m asyncio ps PID``
or ``python -m asyncio pstree PID``.
The ``ps`` subcommand inspects the given process ID (PID) and displays
information about currently running asyncio tasks.
It outputs a task table: a flat listing of all tasks, their names,
their coroutine stacks, and which tasks are awaiting them.
The ``pstree`` subcommand fetches the same information, but instead renders a
visual async call tree, showing coroutine relationships in a hierarchical format.
This command is particularly useful for debugging long-running or stuck
asynchronous programs.
It can help developers quickly identify where a program is blocked,
what tasks are pending, and how coroutines are chained together.
For example given this code:
.. code-block:: python
import asyncio
async def play_track(track):
await asyncio.sleep(5)
print(f'🎵 Finished: {track}')
async def play_album(name, tracks):
async with asyncio.TaskGroup() as tg:
for track in tracks:
tg.create_task(play_track(track), name=track)
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(
play_album('Sundowning', ['TNDNBTG', 'Levitate']),
name='Sundowning')
tg.create_task(
play_album('TMBTE', ['DYWTYLM', 'Aqua Regia']),
name='TMBTE')
if __name__ == '__main__':
asyncio.run(main())
Executing the new tool on the running process will yield a table like this:
.. code-block:: bash
python -m asyncio ps 12345
tid task id task name coroutine stack awaiter chain awaiter name awaiter id
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1935500 0x7fc930c18050 Task-1 TaskGroup._aexit -> TaskGroup.__aexit__ -> main 0x0
1935500 0x7fc930c18230 Sundowning TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fa50 TMBTE TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fdf0 TNDNBTG sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32510 Levitate sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32890 DYWTYLM sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
1935500 0x7fc93161ec30 Aqua Regia sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
or a tree like this:
.. code-block:: bash
python -m asyncio pstree 12345
└── (T) Task-1
└── main example.py:13
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) Sundowning
│ └── album example.py:8
│ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
│ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
│ ├── (T) TNDNBTG
│ │ └── play example.py:4
│ │ └── sleep Lib/asyncio/tasks.py:702
│ └── (T) Levitate
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) TMBTE
└── album example.py:8
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) DYWTYLM
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) Aqua Regia
└── play example.py:4
└── sleep Lib/asyncio/tasks.py:702
If a cycle is detected in the async await graph (which could indicate a
programming issue), the tool raises an error and lists the cycle paths that
prevent tree construction:
.. code-block:: bash
python -m asyncio pstree 12345
ERROR: await-graph contains cycles - cannot print a tree!
cycle: Task-2 → Task-3 → Task-2
(Contributed by Pablo Galindo, Łukasz Langa, Yury Selivanov, and Marta
Gomez Macias in :gh:`91048`.)
.. _whatsnew314-concurrent-warnings-control:
Concurrent safe warnings control
--------------------------------
The :class:`warnings.catch_warnings` context manager will now optionally
use a context variable for warning filters. This is enabled by setting
the :data:`~sys.flags.context_aware_warnings` flag, either with the ``-X``
command-line option or an environment variable. This gives predictable
warnings control when using :class:`~warnings.catch_warnings` combined with
multiple threads or asynchronous tasks. The flag defaults to true for the
free-threaded build and false for the GIL-enabled build.
(Contributed by Neil Schemenauer and Kumar Aditya in :gh:`130010`.)
Other language changes
======================
* All Windows code pages are now supported as 'cpXXX' codecs on Windows.
(Contributed by Serhiy Storchaka in :gh:`123803`.)
* Implement mixed-mode arithmetic rules combining real and complex numbers
as specified by the C standard since C99.
(Contributed by Sergey B Kirpichev in :gh:`69639`.)
* More syntax errors are now detected regardless of optimisation and
the :option:`-O` command-line option.
This includes writes to ``__debug__``, incorrect use of :keyword:`await`,
and asynchronous comprehensions outside asynchronous functions.
For example, ``python -O -c 'assert (__debug__ := 1)'``
or ``python -O -c 'assert await 1'`` now produce :exc:`SyntaxError`\ s.
(Contributed by Irit Katriel and Jelle Zijlstra in :gh:`122245` & :gh:`121637`.)
* When subclassing a pure C type, the C slots for the new type
are no longer replaced with a wrapped version on class creation
if they are not explicitly overridden in the subclass.
(Contributed by Tomasz Pytel in :gh:`132284`.)
Built-ins
---------
* The :meth:`bytes.fromhex` and :meth:`bytearray.fromhex` methods now accept
ASCII :class:`bytes` and :term:`bytes-like objects <bytes-like object>`.
(Contributed by Daniel Pope in :gh:`129349`.)
* Add class methods :meth:`float.from_number` and :meth:`complex.from_number`
to convert a number to :class:`float` or :class:`complex` type correspondingly.
They raise a :exc:`TypeError` if the argument is not a real number.
(Contributed by Serhiy Storchaka in :gh:`84978`.)
* Support underscore and comma as thousands separators in the fractional part
for floating-point presentation types of the new-style string formatting
(with :func:`format` or :ref:`f-strings`).
(Contributed by Sergey B Kirpichev in :gh:`87790`.)
* The :func:`int` function no longer delegates to :meth:`~object.__trunc__`.
Classes that want to support conversion to :func:`!int` must implement
either :meth:`~object.__int__` or :meth:`~object.__index__`.
(Contributed by Mark Dickinson in :gh:`119743`.)
* The :func:`map` function now has an optional keyword-only *strict* flag
like :func:`zip` to check that all the iterables are of equal length.
(Contributed by Wannes Boeykens in :gh:`119793`.)
* The :class:`memoryview` type now supports subscription,
making it a :term:`generic type`.
(Contributed by Brian Schubert in :gh:`126012`.)
* Using :data:`NotImplemented` in a boolean context
will now raise a :exc:`TypeError`.
This has raised a :exc:`DeprecationWarning` since Python 3.9.
(Contributed by Jelle Zijlstra in :gh:`118767`.)
* Three-argument :func:`pow` now tries calling :meth:`~object.__rpow__`
if necessary.
Previously it was only called in two-argument :func:`!pow`
and the binary power operator.
(Contributed by Serhiy Storchaka in :gh:`130104`.)
* :class:`super` objects are now :mod:`copyable <copy>` and :mod:`pickleable
<pickle>`.
(Contributed by Serhiy Storchaka in :gh:`125767`.)
Command line and environment
----------------------------
* The import time flag can now track modules that are already loaded ('cached'),
via the new :option:`-X importtime=2 <-X>`.
When such a module is imported, the ``self`` and ``cumulative`` times
are replaced by the string ``cached``.
Values above ``2`` for ``-X importtime`` are now reserved for future use.
(Contributed by Noah Kim and Adam Turner in :gh:`118655`.)
* The command-line option :option:`-c` now automatically dedents its code
argument before execution.
(Contributed by Jon Crall and Steven Sun in :gh:`103998`.)
* :option:`!-J` is no longer a reserved flag for Jython_,
and now has no special meaning.
(Contributed by Adam Turner in :gh:`133336`.)
.. _Jython: https://www.jython.org/
.. _whatsnew314-bracketless-except:
PEP 758: Allow ``except`` and ``except*`` expressions without brackets
----------------------------------------------------------------------
The :keyword:`except` and :keyword:`except* <except_star>` expressions
now allow brackets to be omitted when there are multiple exception types
and the ``as`` clause is not used.
For example:
.. code-block:: python
try:
connect_to_server()
except TimeoutError, ConnectionRefusedError:
print('The network has ceased to be!')
(Contributed by Pablo Galindo and Brett Cannon in :pep:`758` and :gh:`131831`.)
.. _whatsnew314-finally-syntaxwarning:
PEP 765: Control flow in :keyword:`finally` blocks
--------------------------------------------------
The compiler now emits a :exc:`SyntaxWarning` when a :keyword:`return`,
:keyword:`break`, or :keyword:`continue` statement have the effect of
leaving a :keyword:`finally` block.
This change is specified in :pep:`765`.
In situations where this change is inconvenient (such as those where the
warnings are redundant due to code linting), the :ref:`warning filter
<warning-filter>` can be used to turn off all syntax warnings by adding
``ignore::SyntaxWarning`` as a filter. This can be specified in combination
with a filter that converts other warnings to errors (for example, passing
``-Werror -Wignore::SyntaxWarning`` as CLI options, or setting
``PYTHONWARNINGS=error,ignore::SyntaxWarning``).
Note that applying such a filter at runtime using the :mod:`warnings` module
will only suppress the warning in code that is compiled *after* the filter is
adjusted. Code that is compiled prior to the filter adjustment (for example,
when a module is imported) will still emit the syntax warning.
(Contributed by Irit Katriel in :gh:`130080`.)
.. _incremental-garbage-collection:
.. _whatsnew314-incremental-gc:
Garbage collection
------------------
**From Python 3.14.5 onwards:**
The garbage collector (GC) has changed in Python 3.14.5.
Python 3.14.0-3.14.4 shipped with a new incremental GC.
However, due to a number of `reports
<https://github.com/python/cpython/issues/142516>`__
of significant memory pressure in production environments,
it has been reverted back to the generational GC from 3.13.
This is the GC now used in Python 3.14.5 and later.
**Previously in Python 3.14.0-3.14.4:**
The cycle garbage collector is now incremental.
This means that maximum pause times are reduced
by an order of magnitude or more for larger heaps.
There are now only two generations: young and old.
When :func:`gc.collect` is not called directly, the
GC is invoked a little less frequently. When invoked, it
collects the young generation and an increment of the
old generation, instead of collecting one or more generations.
The behavior of :func:`!gc.collect` changes slightly:
* ``gc.collect(1)``: Performs an increment of garbage collection,
rather than collecting generation 1.
* Other calls to :func:`!gc.collect` are unchanged.
(Contributed by Mark Shannon in :gh:`108362`.)
Default interactive shell
-------------------------
.. _whatsnew314-pyrepl-highlighting:
* The default :term:`interactive` shell now highlights Python syntax.
The feature is enabled by default, save if :envvar:`PYTHON_BASIC_REPL`