• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1****************************
2  What's New In Python 3.10
3****************************
4
5:Editor: Pablo Galindo Salgado
6
7.. Rules for maintenance:
8
9   * Anyone can add text to this document.  Do not spend very much time
10   on the wording of your changes, because your text will probably
11   get rewritten to some degree.
12
13   * The maintainer will go through Misc/NEWS periodically and add
14   changes; it's therefore more important to add your changes to
15   Misc/NEWS than to this file.
16
17   * This is not a complete list of every single change; completeness
18   is the purpose of Misc/NEWS.  Some changes I consider too small
19   or esoteric to include.  If such a change is added to the text,
20   I'll just remove it.  (This is another reason you shouldn't spend
21   too much time on writing your addition.)
22
23   * If you want to draw your new text to the attention of the
24   maintainer, add 'XXX' to the beginning of the paragraph or
25   section.
26
27   * It's OK to just add a fragmentary note about a change.  For
28   example: "XXX Describe the transmogrify() function added to the
29   socket module."  The maintainer will research the change and
30   write the necessary text.
31
32   * You can comment out your additions if you like, but it's not
33   necessary (especially when a final release is some months away).
34
35   * Credit the author of a patch or bugfix.   Just the name is
36   sufficient; the e-mail address isn't necessary.
37
38   * It's helpful to add the bug/patch number as a comment:
39
40   XXX Describe the transmogrify() function added to the socket
41   module.
42   (Contributed by P.Y. Developer in :issue:`12345`.)
43
44   This saves the maintainer the effort of going through the git log
45   when researching a change.
46
47This article explains the new features in Python 3.10, compared to 3.9.
48Python 3.10 was released on October 4, 2021.
49For full details, see the :ref:`changelog <changelog>`.
50
51Summary -- Release highlights
52=============================
53
54.. This section singles out the most important changes in Python 3.10.
55   Brevity is key.
56
57
58.. PEP-sized items next.
59
60New syntax features:
61
62* :pep:`634`, Structural Pattern Matching: Specification
63* :pep:`635`, Structural Pattern Matching: Motivation and Rationale
64* :pep:`636`, Structural Pattern Matching: Tutorial
65* :issue:`12782`, Parenthesized context managers are now officially allowed.
66
67New features in the standard library:
68
69* :pep:`618`, Add Optional Length-Checking To zip.
70
71Interpreter improvements:
72
73* :pep:`626`, Precise line numbers for debugging and other tools.
74
75New typing features:
76
77* :pep:`604`, Allow writing union types as X | Y
78* :pep:`612`, Parameter Specification Variables
79* :pep:`613`, Explicit Type Aliases
80* :pep:`647`, User-Defined Type Guards
81
82Important deprecations, removals or restrictions:
83
84* :pep:`644`, Require OpenSSL 1.1.1 or newer
85* :pep:`632`, Deprecate distutils module.
86* :pep:`623`, Deprecate and prepare for the removal of the wstr member in PyUnicodeObject.
87* :pep:`624`, Remove Py_UNICODE encoder APIs
88* :pep:`597`, Add optional EncodingWarning
89
90
91New Features
92============
93
94.. _whatsnew310-pep563:
95
96Parenthesized context managers
97------------------------------
98
99Using enclosing parentheses for continuation across multiple lines
100in context managers is now supported. This allows formatting a long
101collection of context managers in multiple lines in a similar way
102as it was previously possible with import statements. For instance,
103all these examples are now valid:
104
105.. code-block:: python
106
107    with (CtxManager() as example):
108        ...
109
110    with (
111        CtxManager1(),
112        CtxManager2()
113    ):
114        ...
115
116    with (CtxManager1() as example,
117          CtxManager2()):
118        ...
119
120    with (CtxManager1(),
121          CtxManager2() as example):
122        ...
123
124    with (
125        CtxManager1() as example1,
126        CtxManager2() as example2
127    ):
128        ...
129
130it is also possible to use a trailing comma at the end of the
131enclosed group:
132
133.. code-block:: python
134
135    with (
136        CtxManager1() as example1,
137        CtxManager2() as example2,
138        CtxManager3() as example3,
139    ):
140        ...
141
142This new syntax uses the non LL(1) capacities of the new parser.
143Check :pep:`617` for more details.
144
145(Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou
146in :issue:`12782` and :issue:`40334`.)
147
148
149Better error messages
150---------------------
151
152SyntaxErrors
153~~~~~~~~~~~~
154
155When parsing code that contains unclosed parentheses or brackets the interpreter
156now includes the location of the unclosed bracket of parentheses instead of displaying
157*SyntaxError: unexpected EOF while parsing* or pointing to some incorrect location.
158For instance, consider the following code (notice the unclosed '{'):
159
160.. code-block:: python
161
162    expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
163                38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
164    some_other_code = foo()
165
166Previous versions of the interpreter reported confusing places as the location of
167the syntax error:
168
169.. code-block:: python
170
171   File "example.py", line 3
172       some_other_code = foo()
173                       ^
174   SyntaxError: invalid syntax
175
176but in Python 3.10 a more informative error is emitted:
177
178.. code-block:: python
179
180    File "example.py", line 1
181        expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
182                   ^
183    SyntaxError: '{' was never closed
184
185
186In a similar way, errors involving unclosed string literals (single and triple
187quoted) now point to the start of the string instead of reporting EOF/EOL.
188
189These improvements are inspired by previous work in the PyPy interpreter.
190
191(Contributed by Pablo Galindo in :issue:`42864` and Batuhan Taskaya in
192:issue:`40176`.)
193
194:exc:`SyntaxError` exceptions raised by the interpreter will now highlight the
195full error range of the expression that constitutes the syntax error itself,
196instead of just where the problem is detected. In this way, instead of displaying
197(before Python 3.10):
198
199.. code-block:: python
200
201    >>> foo(x, z for z in range(10), t, w)
202      File "<stdin>", line 1
203        foo(x, z for z in range(10), t, w)
204               ^
205    SyntaxError: Generator expression must be parenthesized
206
207now Python 3.10 will display the exception as:
208
209.. code-block:: python
210
211    >>> foo(x, z for z in range(10), t, w)
212      File "<stdin>", line 1
213        foo(x, z for z in range(10), t, w)
214               ^^^^^^^^^^^^^^^^^^^^
215    SyntaxError: Generator expression must be parenthesized
216
217This improvement was contributed by Pablo Galindo in :issue:`43914`.
218
219A considerable amount of new specialized messages for :exc:`SyntaxError` exceptions
220have been incorporated. Some of the most notable ones are as follows:
221
222* Missing ``:`` before blocks:
223
224  .. code-block:: python
225
226      >>> if rocket.position > event_horizon
227        File "<stdin>", line 1
228          if rocket.position > event_horizon
229                                            ^
230      SyntaxError: expected ':'
231
232  (Contributed by Pablo Galindo in :issue:`42997`.)
233
234* Unparenthesised tuples in comprehensions targets:
235
236  .. code-block:: python
237
238      >>> {x,y for x,y in zip('abcd', '1234')}
239        File "<stdin>", line 1
240          {x,y for x,y in zip('abcd', '1234')}
241           ^
242      SyntaxError: did you forget parentheses around the comprehension target?
243
244  (Contributed by Pablo Galindo in :issue:`43017`.)
245
246* Missing commas in collection literals and between expressions:
247
248  .. code-block:: python
249
250      >>> items = {
251      ... x: 1,
252      ... y: 2
253      ... z: 3,
254        File "<stdin>", line 3
255          y: 2
256             ^
257      SyntaxError: invalid syntax. Perhaps you forgot a comma?
258
259  (Contributed by Pablo Galindo in :issue:`43822`.)
260
261* Multiple Exception types without parentheses:
262
263  .. code-block:: python
264
265      >>> try:
266      ...     build_dyson_sphere()
267      ... except NotEnoughScienceError, NotEnoughResourcesError:
268        File "<stdin>", line 3
269          except NotEnoughScienceError, NotEnoughResourcesError:
270                 ^
271      SyntaxError: multiple exception types must be parenthesized
272
273  (Contributed by Pablo Galindo in :issue:`43149`.)
274
275* Missing ``:`` and values in dictionary literals:
276
277  .. code-block:: python
278
279      >>> values = {
280      ... x: 1,
281      ... y: 2,
282      ... z:
283      ... }
284        File "<stdin>", line 4
285          z:
286           ^
287      SyntaxError: expression expected after dictionary key and ':'
288
289      >>> values = {x:1, y:2, z w:3}
290        File "<stdin>", line 1
291          values = {x:1, y:2, z w:3}
292                              ^
293      SyntaxError: ':' expected after dictionary key
294
295  (Contributed by Pablo Galindo in :issue:`43823`.)
296
297* ``try`` blocks without ``except`` or ``finally`` blocks:
298
299  .. code-block:: python
300
301      >>> try:
302      ...     x = 2
303      ... something = 3
304        File "<stdin>", line 3
305          something  = 3
306          ^^^^^^^^^
307      SyntaxError: expected 'except' or 'finally' block
308
309  (Contributed by Pablo Galindo in :issue:`44305`.)
310
311* Usage of ``=`` instead of ``==`` in comparisons:
312
313  .. code-block:: python
314
315      >>> if rocket.position = event_horizon:
316        File "<stdin>", line 1
317          if rocket.position = event_horizon:
318                             ^
319      SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
320
321  (Contributed by Pablo Galindo in :issue:`43797`.)
322
323* Usage of ``*`` in f-strings:
324
325  .. code-block:: python
326
327      >>> f"Black holes {*all_black_holes} and revelations"
328        File "<stdin>", line 1
329          (*all_black_holes)
330           ^
331      SyntaxError: f-string: cannot use starred expression here
332
333  (Contributed by Pablo Galindo in :issue:`41064`.)
334
335IndentationErrors
336~~~~~~~~~~~~~~~~~
337
338Many :exc:`IndentationError` exceptions now have more context regarding what kind of block
339was expecting an indentation, including the location of the statement:
340
341.. code-block:: python
342
343    >>> def foo():
344    ...    if lel:
345    ...    x = 2
346      File "<stdin>", line 3
347        x = 2
348        ^
349    IndentationError: expected an indented block after 'if' statement in line 2
350
351
352AttributeErrors
353~~~~~~~~~~~~~~~
354
355When printing :exc:`AttributeError`, :c:func:`!PyErr_Display` will offer
356suggestions of similar attribute names in the object that the exception was
357raised from:
358
359.. code-block:: python
360
361    >>> collections.namedtoplo
362    Traceback (most recent call last):
363      File "<stdin>", line 1, in <module>
364    AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?
365
366(Contributed by Pablo Galindo in :issue:`38530`.)
367
368.. warning::
369   Notice this won't work if :c:func:`!PyErr_Display` is not called to display the error
370   which can happen if some other custom error display function is used. This is a common
371   scenario in some REPLs like IPython.
372
373NameErrors
374~~~~~~~~~~
375
376When printing :exc:`NameError` raised by the interpreter, :c:func:`!PyErr_Display`
377will offer suggestions of similar variable names in the function that the exception
378was raised from:
379
380.. code-block:: python
381
382    >>> schwarzschild_black_hole = None
383    >>> schwarschild_black_hole
384    Traceback (most recent call last):
385      File "<stdin>", line 1, in <module>
386    NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?
387
388(Contributed by Pablo Galindo in :issue:`38530`.)
389
390.. warning::
391   Notice this won't work if :c:func:`!PyErr_Display` is not called to display the error,
392   which can happen if some other custom error display function is used. This is a common
393   scenario in some REPLs like IPython.
394
395
396PEP 626: Precise line numbers for debugging and other tools
397-----------------------------------------------------------
398
399PEP 626 brings more precise and reliable line numbers for debugging, profiling and coverage tools.
400Tracing events, with the correct line number, are generated for all lines of code executed and only for lines of code that are executed.
401
402The :attr:`~frame.f_lineno` attribute of frame objects will always contain the
403expected line number.
404
405The :attr:`~codeobject.co_lnotab` attribute of
406:ref:`code objects <code-objects>` is deprecated and
407will be removed in 3.12.
408Code that needs to convert from offset to line number should use the new
409:meth:`~codeobject.co_lines` method instead.
410
411PEP 634: Structural Pattern Matching
412------------------------------------
413
414Structural pattern matching has been added in the form of a *match statement*
415and *case statements* of patterns with associated actions. Patterns
416consist of sequences, mappings, primitive data types as well as class instances.
417Pattern matching enables programs to extract information from complex data types,
418branch on the structure of data, and apply specific actions based on different
419forms of data.
420
421Syntax and operations
422~~~~~~~~~~~~~~~~~~~~~
423
424The generic syntax of pattern matching is::
425
426      match subject:
427          case <pattern_1>:
428              <action_1>
429          case <pattern_2>:
430              <action_2>
431          case <pattern_3>:
432              <action_3>
433          case _:
434              <action_wildcard>
435
436A match statement takes an expression and compares its value to successive
437patterns given as one or more case blocks.  Specifically, pattern matching
438operates by:
439
4401. using data with type and shape (the ``subject``)
4412. evaluating the ``subject`` in the ``match`` statement
4423. comparing the subject with each pattern in a ``case`` statement
443   from top to bottom until a match is confirmed.
4444. executing the action associated with the pattern of the confirmed
445   match
4465. If an exact match is not confirmed, the last case, a wildcard ``_``,
447   if provided, will be used as the matching case. If an exact match is
448   not confirmed and a wildcard case does not exist, the entire match
449   block is a no-op.
450
451Declarative approach
452~~~~~~~~~~~~~~~~~~~~
453
454Readers may be aware of pattern matching through the simple example of matching
455a subject (data object) to a literal (pattern) with the switch statement found
456in C, Java or JavaScript (and many other languages). Often the switch statement
457is used for comparison of an object/expression with case statements containing
458literals.
459
460More powerful examples of pattern matching can be found in languages such as
461Scala and Elixir. With structural pattern matching, the approach is "declarative" and
462explicitly states the conditions (the patterns) for data to match.
463
464While an "imperative" series of instructions using nested "if" statements
465could be used to accomplish something similar to structural pattern matching,
466it is less clear than the "declarative" approach. Instead the "declarative"
467approach states the conditions to meet for a match and is more readable through
468its explicit patterns. While structural pattern matching can be used in its
469simplest form comparing a variable to a literal in a case statement, its
470true value for Python lies in its handling of the subject's type and shape.
471
472Simple pattern: match to a literal
473~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
474
475Let's look at this example as pattern matching in its simplest form: a value,
476the subject, being matched to several literals, the patterns. In the example
477below, ``status`` is the subject of the match statement. The patterns are
478each of the case statements, where literals represent request status codes.
479The associated action to the case is executed after a match::
480
481    def http_error(status):
482        match status:
483            case 400:
484                return "Bad request"
485            case 404:
486                return "Not found"
487            case 418:
488                return "I'm a teapot"
489            case _:
490                return "Something's wrong with the internet"
491
492If the above function is passed a ``status`` of 418, "I'm a teapot" is returned.
493If the above function is passed a ``status`` of 500, the case statement with
494``_`` will match as a wildcard, and "Something's wrong with the internet" is
495returned.
496Note the last block: the variable name, ``_``, acts as a *wildcard* and insures
497the subject will always match. The use of ``_`` is optional.
498
499You can combine several literals in a single pattern using ``|`` ("or")::
500
501            case 401 | 403 | 404:
502                return "Not allowed"
503
504Behavior without the wildcard
505^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
506
507If we modify the above example by removing the last case block, the example
508becomes::
509
510    def http_error(status):
511        match status:
512            case 400:
513                return "Bad request"
514            case 404:
515                return "Not found"
516            case 418:
517                return "I'm a teapot"
518
519Without the use of ``_`` in a case statement, a match may not exist. If no
520match exists, the behavior is a no-op. For example, if ``status`` of 500 is
521passed, a no-op occurs.
522
523Patterns with a literal and variable
524~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
525
526Patterns can look like unpacking assignments, and a pattern may be used to bind
527variables. In this example, a data point can be unpacked to its x-coordinate
528and y-coordinate::
529
530    # point is an (x, y) tuple
531    match point:
532        case (0, 0):
533            print("Origin")
534        case (0, y):
535            print(f"Y={y}")
536        case (x, 0):
537            print(f"X={x}")
538        case (x, y):
539            print(f"X={x}, Y={y}")
540        case _:
541            raise ValueError("Not a point")
542
543The first pattern has two literals, ``(0, 0)``, and may be thought of as an
544extension of the literal pattern shown above. The next two patterns combine a
545literal and a variable, and the variable *binds* a value from the subject
546(``point``).  The fourth pattern captures two values, which makes it
547conceptually similar to the unpacking assignment ``(x, y) = point``.
548
549Patterns and classes
550~~~~~~~~~~~~~~~~~~~~
551
552If you are using classes to structure your data, you can use as a pattern
553the class name followed by an argument list resembling a constructor. This
554pattern has the ability to capture class attributes into variables::
555
556    class Point:
557        x: int
558        y: int
559
560    def location(point):
561        match point:
562            case Point(x=0, y=0):
563                print("Origin is the point's location.")
564            case Point(x=0, y=y):
565                print(f"Y={y} and the point is on the y-axis.")
566            case Point(x=x, y=0):
567                print(f"X={x} and the point is on the x-axis.")
568            case Point():
569                print("The point is located somewhere else on the plane.")
570            case _:
571                print("Not a point")
572
573Patterns with positional parameters
574^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
575
576You can use positional parameters with some builtin classes that provide an
577ordering for their attributes (e.g. dataclasses). You can also define a specific
578position for attributes in patterns by setting the ``__match_args__`` special
579attribute in your classes. If it's set to ("x", "y"), the following patterns
580are all equivalent (and all bind the ``y`` attribute to the ``var`` variable)::
581
582    Point(1, var)
583    Point(1, y=var)
584    Point(x=1, y=var)
585    Point(y=var, x=1)
586
587Nested patterns
588~~~~~~~~~~~~~~~
589
590Patterns can be arbitrarily nested.  For example, if our data is a short
591list of points, it could be matched like this::
592
593    match points:
594        case []:
595            print("No points in the list.")
596        case [Point(0, 0)]:
597            print("The origin is the only point in the list.")
598        case [Point(x, y)]:
599            print(f"A single point {x}, {y} is in the list.")
600        case [Point(0, y1), Point(0, y2)]:
601            print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
602        case _:
603            print("Something else is found in the list.")
604
605Complex patterns and the wildcard
606~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
607
608To this point, the examples have used ``_`` alone in the last case statement.
609A wildcard can be used in more complex patterns, such as ``('error', code, _)``.
610For example::
611
612   match test_variable:
613       case ('warning', code, 40):
614           print("A warning has been received.")
615       case ('error', code, _):
616           print(f"An error {code} occurred.")
617
618In the above case, ``test_variable`` will match for ('error', code, 100) and
619('error', code, 800).
620
621Guard
622~~~~~
623
624We can add an ``if`` clause to a pattern, known as a "guard".  If the
625guard is false, ``match`` goes on to try the next case block.  Note
626that value capture happens before the guard is evaluated::
627
628    match point:
629        case Point(x, y) if x == y:
630            print(f"The point is located on the diagonal Y=X at {x}.")
631        case Point(x, y):
632            print(f"Point is not on the diagonal.")
633
634Other Key Features
635~~~~~~~~~~~~~~~~~~
636
637Several other key features:
638
639- Like unpacking assignments, tuple and list patterns have exactly the
640  same meaning and actually match arbitrary sequences. Technically,
641  the subject must be a sequence.
642  Therefore, an important exception is that patterns don't match iterators.
643  Also, to prevent a common mistake, sequence patterns don't match strings.
644
645- Sequence patterns support wildcards: ``[x, y, *rest]`` and ``(x, y,
646  *rest)`` work similar to wildcards in unpacking assignments.  The
647  name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence
648  of at least two items without binding the remaining items.
649
650- Mapping patterns: ``{"bandwidth": b, "latency": l}`` captures the
651  ``"bandwidth"`` and ``"latency"`` values from a dict.  Unlike sequence
652  patterns, extra keys are ignored.  A wildcard ``**rest`` is also
653  supported.  (But ``**_`` would be redundant, so is not allowed.)
654
655- Subpatterns may be captured using the ``as`` keyword::
656
657      case (Point(x1, y1), Point(x2, y2) as p2): ...
658
659  This binds x1, y1, x2, y2 like you would expect without the ``as`` clause,
660  and p2 to the entire second item of the subject.
661
662- Most literals are compared by equality. However, the singletons ``True``,
663  ``False`` and ``None`` are compared by identity.
664
665- Named constants may be used in patterns.  These named constants must be
666  dotted names to prevent the constant from being interpreted as a capture
667  variable::
668
669      from enum import Enum
670      class Color(Enum):
671          RED = 0
672          GREEN = 1
673          BLUE = 2
674
675      color = Color.GREEN
676      match color:
677          case Color.RED:
678              print("I see red!")
679          case Color.GREEN:
680              print("Grass is green")
681          case Color.BLUE:
682              print("I'm feeling the blues :(")
683
684For the full specification see :pep:`634`.  Motivation and rationale
685are in :pep:`635`, and a longer tutorial is in :pep:`636`.
686
687
688.. _whatsnew310-pep597:
689
690Optional ``EncodingWarning`` and ``encoding="locale"`` option
691-------------------------------------------------------------
692
693The default encoding of :class:`~io.TextIOWrapper` and :func:`open` is
694platform and locale dependent. Since UTF-8 is used on most Unix
695platforms, omitting ``encoding`` option when opening UTF-8 files
696(e.g. JSON, YAML, TOML, Markdown) is a very common bug. For example::
697
698   # BUG: "rb" mode or encoding="utf-8" should be used.
699   with open("data.json") as f:
700       data = json.load(f)
701
702To find this type of bug, an optional ``EncodingWarning`` is added.
703It is emitted when :data:`sys.flags.warn_default_encoding <sys.flags>`
704is true and locale-specific default encoding is used.
705
706``-X warn_default_encoding`` option and :envvar:`PYTHONWARNDEFAULTENCODING`
707are added to enable the warning.
708
709See :ref:`io-text-encoding` for more information.
710
711.. _new-feat-related-type-hints:
712
713New Features Related to Type Hints
714==================================
715
716This section covers major changes affecting :pep:`484` type hints and
717the :mod:`typing` module.
718
719
720PEP 604: New Type Union Operator
721--------------------------------
722
723A new type union operator was introduced which enables the syntax ``X | Y``.
724This provides a cleaner way of expressing 'either type X or type Y' instead of
725using :data:`typing.Union`, especially in type hints.
726
727In previous versions of Python, to apply a type hint for functions accepting
728arguments of multiple types, :data:`typing.Union` was used::
729
730   def square(number: Union[int, float]) -> Union[int, float]:
731       return number ** 2
732
733
734Type hints can now be written in a more succinct manner::
735
736   def square(number: int | float) -> int | float:
737       return number ** 2
738
739
740This new syntax is also accepted as the second argument to :func:`isinstance`
741and :func:`issubclass`::
742
743   >>> isinstance(1, int | str)
744   True
745
746See :ref:`types-union` and :pep:`604` for more details.
747
748(Contributed by Maggie Moss and Philippe Prados in :issue:`41428`,
749with additions by Yurii Karabas and Serhiy Storchaka in :issue:`44490`.)
750
751
752PEP 612: Parameter Specification Variables
753------------------------------------------
754
755Two new options to improve the information provided to static type checkers for
756:pep:`484`\ 's ``Callable`` have been added to the :mod:`typing` module.
757
758The first is the parameter specification variable.  They are used to forward the
759parameter types of one callable to another callable -- a pattern commonly
760found in higher order functions and decorators.  Examples of usage can be found
761in :class:`typing.ParamSpec`. Previously, there was no easy way to type annotate
762dependency of parameter types in such a precise manner.
763
764The second option is the new ``Concatenate`` operator. It's used in conjunction
765with parameter specification variables to type annotate a higher order callable
766which adds or removes parameters of another callable.  Examples of usage can
767be found in :class:`typing.Concatenate`.
768
769See :class:`typing.Callable`, :class:`typing.ParamSpec`,
770:class:`typing.Concatenate`, :class:`typing.ParamSpecArgs`,
771:class:`typing.ParamSpecKwargs`, and :pep:`612` for more details.
772
773(Contributed by Ken Jin in :issue:`41559`, with minor enhancements by Jelle
774Zijlstra in :issue:`43783`.  PEP written by Mark Mendoza.)
775
776
777PEP 613: TypeAlias
778------------------
779
780:pep:`484` introduced the concept of type aliases, only requiring them to be
781top-level unannotated assignments. This simplicity sometimes made it difficult
782for type checkers to distinguish between type aliases and ordinary assignments,
783especially when forward references or invalid types were involved. Compare::
784
785   StrCache = 'Cache[str]'  # a type alias
786   LOG_PREFIX = 'LOG[DEBUG]'  # a module constant
787
788Now the :mod:`typing` module has a special value :data:`~typing.TypeAlias`
789which lets you declare type aliases more explicitly::
790
791   StrCache: TypeAlias = 'Cache[str]'  # a type alias
792   LOG_PREFIX = 'LOG[DEBUG]'  # a module constant
793
794See :pep:`613` for more details.
795
796(Contributed by Mikhail Golubev in :issue:`41923`.)
797
798PEP 647: User-Defined Type Guards
799---------------------------------
800
801:data:`~typing.TypeGuard` has been added to the :mod:`typing` module to annotate
802type guard functions and improve information provided to static type checkers
803during type narrowing.  For more information, please see
804:data:`~typing.TypeGuard`\ 's documentation, and :pep:`647`.
805
806(Contributed by Ken Jin and Guido van Rossum in :issue:`43766`.
807PEP written by Eric Traut.)
808
809Other Language Changes
810======================
811
812* The :class:`int` type has a new method :meth:`int.bit_count`, returning the
813  number of ones in the binary expansion of a given integer, also known
814  as the population count. (Contributed by Niklas Fiekas in :issue:`29882`.)
815
816* The views returned by :meth:`dict.keys`, :meth:`dict.values` and
817  :meth:`dict.items` now all have a ``mapping`` attribute that gives a
818  :class:`types.MappingProxyType` object wrapping the original
819  dictionary. (Contributed by Dennis Sweeney in :issue:`40890`.)
820
821* :pep:`618`: The :func:`zip` function now has an optional ``strict`` flag, used
822  to require that all the iterables have an equal length.
823
824* Builtin and extension functions that take integer arguments no longer accept
825  :class:`~decimal.Decimal`\ s, :class:`~fractions.Fraction`\ s and other
826  objects that can be converted to integers only with a loss (e.g. that have
827  the :meth:`~object.__int__` method but do not have the
828  :meth:`~object.__index__` method).
829  (Contributed by Serhiy Storchaka in :issue:`37999`.)
830
831* If :func:`object.__ipow__` returns :data:`NotImplemented`, the operator will
832  correctly fall back to :func:`object.__pow__` and :func:`object.__rpow__` as expected.
833  (Contributed by Alex Shkop in :issue:`38302`.)
834
835* Assignment expressions can now be used unparenthesized within set literals
836  and set comprehensions, as well as in sequence indexes (but not slices).
837
838* Functions have a new ``__builtins__`` attribute which is used to look for
839  builtin symbols when a function is executed, instead of looking into
840  ``__globals__['__builtins__']``. The attribute is initialized from
841  ``__globals__["__builtins__"]`` if it exists, else from the current builtins.
842  (Contributed by Mark Shannon in :issue:`42990`.)
843
844* Two new builtin functions -- :func:`aiter` and :func:`anext` have been added
845  to provide asynchronous counterparts to :func:`iter` and :func:`next`,
846  respectively.
847  (Contributed by Joshua Bronson, Daniel Pope, and Justin Wang in :issue:`31861`.)
848
849* Static methods (:func:`@staticmethod <staticmethod>`) and class methods
850  (:func:`@classmethod <classmethod>`) now inherit the method attributes
851  (``__module__``, ``__name__``, ``__qualname__``, ``__doc__``,
852  ``__annotations__``) and have a new ``__wrapped__`` attribute.
853  Moreover, static methods are now callable as regular functions.
854  (Contributed by Victor Stinner in :issue:`43682`.)
855
856* Annotations for complex targets (everything beside ``simple name`` targets
857  defined by :pep:`526`) no longer cause any runtime effects with ``from __future__ import annotations``.
858  (Contributed by Batuhan Taskaya in :issue:`42737`.)
859
860* Class and module objects now lazy-create empty annotations dicts on demand.
861  The annotations dicts are stored in the object’s ``__dict__`` for
862  backwards compatibility.  This improves the best practices for working
863  with ``__annotations__``; for more information, please see
864  :ref:`annotations-howto`.
865  (Contributed by Larry Hastings in :issue:`43901`.)
866
867* Annotations consist of ``yield``, ``yield from``, ``await`` or named expressions
868  are now forbidden under ``from __future__ import annotations`` due to their side
869  effects.
870  (Contributed by Batuhan Taskaya in :issue:`42725`.)
871
872* Usage of unbound variables, ``super()`` and other expressions that might
873  alter the processing of symbol table as annotations are now rendered
874  effectless under ``from __future__ import annotations``.
875  (Contributed by Batuhan Taskaya in :issue:`42725`.)
876
877* Hashes of NaN values of both :class:`float` type and
878  :class:`decimal.Decimal` type now depend on object identity. Formerly, they
879  always hashed to ``0`` even though NaN values are not equal to one another.
880  This caused potentially quadratic runtime behavior due to excessive hash
881  collisions when creating dictionaries and sets containing multiple NaNs.
882  (Contributed by Raymond Hettinger in :issue:`43475`.)
883
884* A :exc:`SyntaxError` (instead of a :exc:`NameError`) will be raised when deleting
885  the :const:`__debug__` constant.  (Contributed by Donghee Na in :issue:`45000`.)
886
887* :exc:`SyntaxError` exceptions now have ``end_lineno`` and
888  ``end_offset`` attributes.  They will be ``None`` if not determined.
889  (Contributed by Pablo Galindo in :issue:`43914`.)
890
891New Modules
892===========
893
894* None.
895
896
897Improved Modules
898================
899
900asyncio
901-------
902
903Add missing :meth:`~asyncio.events.AbstractEventLoop.connect_accepted_socket`
904method.
905(Contributed by Alex Grönholm in :issue:`41332`.)
906
907argparse
908--------
909
910Misleading phrase "optional arguments" was replaced with "options" in argparse help. Some tests might require adaptation if they rely on exact output match.
911(Contributed by Raymond Hettinger in :issue:`9694`.)
912
913array
914-----
915
916The :meth:`~array.array.index` method of :class:`array.array` now has
917optional *start* and *stop* parameters.
918(Contributed by Anders Lorentsen and Zackery Spytz in :issue:`31956`.)
919
920asynchat, asyncore, smtpd
921-------------------------
922These modules have been marked as deprecated in their module documentation
923since Python 3.6.  An import-time :class:`DeprecationWarning` has now been
924added to all three of these modules.
925
926base64
927------
928
929Add :func:`base64.b32hexencode` and :func:`base64.b32hexdecode` to support the
930Base32 Encoding with Extended Hex Alphabet.
931
932bdb
933---
934
935Add :meth:`~bdb.Breakpoint.clearBreakpoints` to reset all set breakpoints.
936(Contributed by Irit Katriel in :issue:`24160`.)
937
938bisect
939------
940
941Added the possibility of providing a *key* function to the APIs in the :mod:`bisect`
942module. (Contributed by Raymond Hettinger in :issue:`4356`.)
943
944codecs
945------
946
947Add a :func:`codecs.unregister` function to unregister a codec search function.
948(Contributed by Hai Shi in :issue:`41842`.)
949
950collections.abc
951---------------
952
953The ``__args__`` of the :ref:`parameterized generic <types-genericalias>` for
954:class:`collections.abc.Callable` are now consistent with :data:`typing.Callable`.
955:class:`collections.abc.Callable` generic now flattens type parameters, similar
956to what :data:`typing.Callable` currently does.  This means that
957``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
958``(int, str, str)``; previously this was ``([int, str], str)``.  To allow this
959change, :class:`types.GenericAlias` can now be subclassed, and a subclass will
960be returned when subscripting the :class:`collections.abc.Callable` type.  Note
961that a :exc:`TypeError` may be raised for invalid forms of parameterizing
962:class:`collections.abc.Callable` which may have passed silently in Python 3.9.
963(Contributed by Ken Jin in :issue:`42195`.)
964
965contextlib
966----------
967
968Add a :func:`contextlib.aclosing` context manager to safely close async generators
969and objects representing asynchronously released resources.
970(Contributed by Joongi Kim and John Belmonte in :issue:`41229`.)
971
972Add asynchronous context manager support to :func:`contextlib.nullcontext`.
973(Contributed by Tom Gringauz in :issue:`41543`.)
974
975Add :class:`~contextlib.AsyncContextDecorator`, for supporting usage of async
976context managers as decorators.
977
978curses
979------
980
981The extended color functions added in ncurses 6.1 will be used transparently
982by :func:`curses.color_content`, :func:`curses.init_color`,
983:func:`curses.init_pair`, and :func:`curses.pair_content`. A new function,
984:func:`curses.has_extended_color_support`, indicates whether extended color
985support is provided by the underlying ncurses library.
986(Contributed by Jeffrey Kintscher and Hans Petter Jansson in :issue:`36982`.)
987
988The ``BUTTON5_*`` constants are now exposed in the :mod:`curses` module if
989they are provided by the underlying curses library.
990(Contributed by Zackery Spytz in :issue:`39273`.)
991
992dataclasses
993-----------
994
995__slots__
996~~~~~~~~~
997
998Added ``slots`` parameter in :func:`dataclasses.dataclass` decorator.
999(Contributed by Yurii Karabas in :issue:`42269`)
1000
1001Keyword-only fields
1002~~~~~~~~~~~~~~~~~~~
1003
1004dataclasses now supports fields that are keyword-only in the
1005generated __init__ method.  There are a number of ways of specifying
1006keyword-only fields.
1007
1008You can say that every field is keyword-only:
1009
1010.. code-block:: python
1011
1012    from dataclasses import dataclass
1013
1014    @dataclass(kw_only=True)
1015    class Birthday:
1016        name: str
1017        birthday: datetime.date
1018
1019Both ``name`` and ``birthday`` are keyword-only parameters to the
1020generated __init__ method.
1021
1022You can specify keyword-only on a per-field basis:
1023
1024.. code-block:: python
1025
1026    from dataclasses import dataclass, field
1027
1028    @dataclass
1029    class Birthday:
1030        name: str
1031        birthday: datetime.date = field(kw_only=True)
1032
1033Here only ``birthday`` is keyword-only.  If you set ``kw_only`` on
1034individual fields, be aware that there are rules about re-ordering
1035fields due to keyword-only fields needing to follow non-keyword-only
1036fields.  See the full dataclasses documentation for details.
1037
1038You can also specify that all fields following a KW_ONLY marker are
1039keyword-only.  This will probably be the most common usage:
1040
1041.. code-block:: python
1042
1043    from dataclasses import dataclass, KW_ONLY
1044
1045    @dataclass
1046    class Point:
1047        x: float
1048        y: float
1049        _: KW_ONLY
1050        z: float = 0.0
1051        t: float = 0.0
1052
1053Here, ``z`` and ``t`` are keyword-only parameters, while ``x`` and
1054``y`` are not.
1055(Contributed by Eric V. Smith in :issue:`43532`.)
1056
1057.. _distutils-deprecated:
1058
1059distutils
1060---------
1061
1062The entire ``distutils`` package is deprecated, to be removed in Python
10633.12. Its functionality for specifying package builds has already been
1064completely replaced by third-party packages ``setuptools`` and
1065``packaging``, and most other commonly used APIs are available elsewhere
1066in the standard library (such as :mod:`platform`, :mod:`shutil`,
1067:mod:`subprocess` or :mod:`sysconfig`). There are no plans to migrate
1068any other functionality from ``distutils``, and applications that are
1069using other functions should plan to make private copies of the code.
1070Refer to :pep:`632` for discussion.
1071
1072The ``bdist_wininst`` command deprecated in Python 3.8 has been removed.
1073The ``bdist_wheel`` command is now recommended to distribute binary packages
1074on Windows.
1075(Contributed by Victor Stinner in :issue:`42802`.)
1076
1077doctest
1078-------
1079
1080When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
1081(Contributed by Brett Cannon in :issue:`42133`.)
1082
1083encodings
1084---------
1085
1086:func:`encodings.normalize_encoding` now ignores non-ASCII characters.
1087(Contributed by Hai Shi in :issue:`39337`.)
1088
1089enum
1090----
1091
1092:class:`~enum.Enum` :func:`~object.__repr__` now returns ``enum_name.member_name`` and
1093:func:`~object.__str__` now returns ``member_name``.  Stdlib enums available as
1094module constants have a :func:`repr` of ``module_name.member_name``.
1095(Contributed by Ethan Furman in :issue:`40066`.)
1096
1097Add :class:`enum.StrEnum` for enums where all members are strings.
1098(Contributed by Ethan Furman in :issue:`41816`.)
1099
1100fileinput
1101---------
1102
1103Add *encoding* and *errors* parameters in :func:`fileinput.input` and
1104:class:`fileinput.FileInput`.
1105(Contributed by Inada Naoki in :issue:`43712`.)
1106
1107:func:`fileinput.hook_compressed` now returns :class:`~io.TextIOWrapper` object
1108when *mode* is "r" and file is compressed, like uncompressed files.
1109(Contributed by Inada Naoki in :issue:`5758`.)
1110
1111faulthandler
1112------------
1113
1114The :mod:`faulthandler` module now detects if a fatal error occurs during a
1115garbage collector collection.
1116(Contributed by Victor Stinner in :issue:`44466`.)
1117
1118gc
1119--
1120
1121Add audit hooks for :func:`gc.get_objects`, :func:`gc.get_referrers` and
1122:func:`gc.get_referents`. (Contributed by Pablo Galindo in :issue:`43439`.)
1123
1124glob
1125----
1126
1127Add the *root_dir* and *dir_fd* parameters in :func:`~glob.glob` and
1128:func:`~glob.iglob` which allow to specify the root directory for searching.
1129(Contributed by Serhiy Storchaka in :issue:`38144`.)
1130
1131hashlib
1132-------
1133
1134The hashlib module requires OpenSSL 1.1.1 or newer.
1135(Contributed by Christian Heimes in :pep:`644` and :issue:`43669`.)
1136
1137The hashlib module has preliminary support for OpenSSL 3.0.0.
1138(Contributed by Christian Heimes in :issue:`38820` and other issues.)
1139
1140The pure-Python fallback of :func:`~hashlib.pbkdf2_hmac` is deprecated. In
1141the future PBKDF2-HMAC will only be available when Python has been built with
1142OpenSSL support.
1143(Contributed by Christian Heimes in :issue:`43880`.)
1144
1145hmac
1146----
1147
1148The hmac module now uses OpenSSL's HMAC implementation internally.
1149(Contributed by Christian Heimes in :issue:`40645`.)
1150
1151IDLE and idlelib
1152----------------
1153
1154Make IDLE invoke :func:`sys.excepthook` (when started without '-n').
1155User hooks were previously ignored.  (Contributed by Ken Hilton in
1156:issue:`43008`.)
1157
1158Rearrange the settings dialog.  Split the General tab into Windows
1159and Shell/Ed tabs.  Move help sources, which extend the Help menu, to the
1160Extensions tab.  Make space for new options and shorten the dialog. The
1161latter makes the dialog better fit small screens.  (Contributed by Terry Jan
1162Reedy in :issue:`40468`.)  Move the indent space setting from the Font tab to
1163the new Windows tab.  (Contributed by Mark Roseman and Terry Jan Reedy in
1164:issue:`33962`.)
1165
1166The changes above were backported to a 3.9 maintenance release.
1167
1168Add a Shell sidebar.  Move the primary prompt ('>>>') to the sidebar.
1169Add secondary prompts ('...') to the sidebar.  Left click and optional
1170drag selects one or more lines of text, as with the editor
1171line number sidebar.  Right click after selecting text lines displays
1172a context menu with 'copy with prompts'.  This zips together prompts
1173from the sidebar with lines from the selected text.  This option also
1174appears on the context menu for the text.  (Contributed by Tal Einat
1175in :issue:`37903`.)
1176
1177Use spaces instead of tabs to indent interactive code.  This makes
1178interactive code entries 'look right'.  Making this feasible was a
1179major motivation for adding the shell sidebar.  (Contributed by
1180Terry Jan Reedy in :issue:`37892`.)
1181
1182Highlight the new :ref:`soft keywords <soft-keywords>` :keyword:`match`,
1183:keyword:`case <match>`, and :keyword:`_ <wildcard-patterns>` in
1184pattern-matching statements. However, this highlighting is not perfect
1185and will be incorrect in some rare cases, including some ``_``-s in
1186``case`` patterns.  (Contributed by Tal Einat in :issue:`44010`.)
1187
1188New in 3.10 maintenance releases.
1189
1190Apply syntax highlighting to ``.pyi`` files. (Contributed by Alex
1191Waygood and Terry Jan Reedy in :issue:`45447`.)
1192
1193Include prompts when saving Shell with inputs and outputs.
1194(Contributed by Terry Jan Reedy in :gh:`95191`.)
1195
1196importlib.metadata
1197------------------
1198
1199Feature parity with ``importlib_metadata`` 4.6
1200(`history <https://importlib-metadata.readthedocs.io/en/latest/history.html>`_).
1201
1202:ref:`importlib.metadata entry points <entry-points>`
1203now provide a nicer experience
1204for selecting entry points by group and name through a new
1205:ref:`importlib.metadata.EntryPoints <entry-points>` class. See the Compatibility
1206Note in the docs for more info on the deprecation and usage.
1207
1208Added :ref:`importlib.metadata.packages_distributions() <package-distributions>`
1209for resolving top-level Python modules and packages to their
1210:ref:`importlib.metadata.Distribution <distributions>`.
1211
1212inspect
1213-------
1214
1215When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
1216(Contributed by Brett Cannon in :issue:`42133`.)
1217
1218Add :func:`inspect.get_annotations`, which safely computes the annotations
1219defined on an object. It works around the quirks of accessing the annotations
1220on various types of objects, and makes very few assumptions about the object
1221it examines. :func:`inspect.get_annotations` can also correctly un-stringize
1222stringized annotations.  :func:`inspect.get_annotations` is now considered
1223best practice for accessing the annotations dict defined on any Python object;
1224for more information on best practices for working with annotations, please see
1225:ref:`annotations-howto`.
1226Relatedly, :func:`inspect.signature`,
1227:func:`inspect.Signature.from_callable`, and :func:`!inspect.Signature.from_function`
1228now call :func:`inspect.get_annotations` to retrieve annotations. This means
1229:func:`inspect.signature` and :func:`inspect.Signature.from_callable` can
1230also now un-stringize stringized annotations.
1231(Contributed by Larry Hastings in :issue:`43817`.)
1232
1233itertools
1234---------
1235
1236Add :func:`itertools.pairwise`.
1237(Contributed by Raymond Hettinger in :issue:`38200`.)
1238
1239linecache
1240---------
1241
1242When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
1243(Contributed by Brett Cannon in :issue:`42133`.)
1244
1245os
1246--
1247
1248Add :func:`os.cpu_count` support for VxWorks RTOS.
1249(Contributed by Peixing Xin in :issue:`41440`.)
1250
1251Add a new function :func:`os.eventfd` and related helpers to wrap the
1252``eventfd2`` syscall on Linux.
1253(Contributed by Christian Heimes in :issue:`41001`.)
1254
1255Add :func:`os.splice` that allows to move data between two file
1256descriptors without copying between kernel address space and user
1257address space, where one of the file descriptors must refer to a
1258pipe. (Contributed by Pablo Galindo in :issue:`41625`.)
1259
1260Add :const:`~os.O_EVTONLY`, :const:`~os.O_FSYNC`, :const:`~os.O_SYMLINK`
1261and :const:`~os.O_NOFOLLOW_ANY` for macOS.
1262(Contributed by Donghee Na in :issue:`43106`.)
1263
1264os.path
1265-------
1266
1267:func:`os.path.realpath` now accepts a *strict* keyword-only argument. When set
1268to ``True``, :exc:`OSError` is raised if a path doesn't exist or a symlink loop
1269is encountered.
1270(Contributed by Barney Gale in :issue:`43757`.)
1271
1272pathlib
1273-------
1274
1275Add slice support to :attr:`PurePath.parents <pathlib.PurePath.parents>`.
1276(Contributed by Joshua Cannon in :issue:`35498`.)
1277
1278Add negative indexing support to :attr:`PurePath.parents
1279<pathlib.PurePath.parents>`.
1280(Contributed by Yaroslav Pankovych in :issue:`21041`.)
1281
1282Add :meth:`Path.hardlink_to <pathlib.Path.hardlink_to>` method that
1283supersedes :meth:`!link_to`. The new method has the same argument
1284order as :meth:`~pathlib.Path.symlink_to`.
1285(Contributed by Barney Gale in :issue:`39950`.)
1286
1287:meth:`pathlib.Path.stat` and :meth:`~pathlib.Path.chmod` now accept a
1288*follow_symlinks* keyword-only argument for consistency with corresponding
1289functions in the :mod:`os` module.
1290(Contributed by Barney Gale in :issue:`39906`.)
1291
1292platform
1293--------
1294
1295Add :func:`platform.freedesktop_os_release` to retrieve operation system
1296identification from `freedesktop.org os-release
1297<https://www.freedesktop.org/software/systemd/man/os-release.html>`_ standard file.
1298(Contributed by Christian Heimes in :issue:`28468`.)
1299
1300pprint
1301------
1302
1303:func:`pprint.pprint` now accepts a new ``underscore_numbers`` keyword argument.
1304(Contributed by sblondon in :issue:`42914`.)
1305
1306:mod:`pprint` can now pretty-print :class:`dataclasses.dataclass` instances.
1307(Contributed by Lewis Gaul in :issue:`43080`.)
1308
1309py_compile
1310----------
1311
1312Add ``--quiet`` option to command-line interface of :mod:`py_compile`.
1313(Contributed by Gregory Schevchenko in :issue:`38731`.)
1314
1315pyclbr
1316------
1317
1318Add an ``end_lineno`` attribute to the ``Function`` and ``Class``
1319objects in the tree returned by :func:`pyclbr.readmodule` and
1320:func:`pyclbr.readmodule_ex`.  It matches the existing (start) ``lineno``.
1321(Contributed by Aviral Srivastava in :issue:`38307`.)
1322
1323shelve
1324------
1325
1326The :mod:`shelve` module now uses :const:`pickle.DEFAULT_PROTOCOL` by default
1327instead of :mod:`pickle` protocol ``3`` when creating shelves.
1328(Contributed by Zackery Spytz in :issue:`34204`.)
1329
1330statistics
1331----------
1332
1333Add :func:`~statistics.covariance`, Pearson's
1334:func:`~statistics.correlation`, and simple
1335:func:`~statistics.linear_regression` functions.
1336(Contributed by Tymoteusz Wołodźko in :issue:`38490`.)
1337
1338site
1339----
1340
1341When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
1342(Contributed by Brett Cannon in :issue:`42133`.)
1343
1344socket
1345------
1346
1347The exception :exc:`socket.timeout` is now an alias of :exc:`TimeoutError`.
1348(Contributed by Christian Heimes in :issue:`42413`.)
1349
1350Add option to create MPTCP sockets with ``IPPROTO_MPTCP``
1351(Contributed by Rui Cunha in :issue:`43571`.)
1352
1353Add ``IP_RECVTOS`` option to receive the type of service (ToS) or DSCP/ECN fields
1354(Contributed by Georg Sauthoff in :issue:`44077`.)
1355
1356ssl
1357---
1358
1359The ssl module requires OpenSSL 1.1.1 or newer.
1360(Contributed by Christian Heimes in :pep:`644` and :issue:`43669`.)
1361
1362The ssl module has preliminary support for OpenSSL 3.0.0 and new option
1363:const:`~ssl.OP_IGNORE_UNEXPECTED_EOF`.
1364(Contributed by Christian Heimes in :issue:`38820`, :issue:`43794`,
1365:issue:`43788`, :issue:`43791`, :issue:`43799`, :issue:`43920`,
1366:issue:`43789`, and :issue:`43811`.)
1367
1368Deprecated function and use of deprecated constants now result in
1369a :exc:`DeprecationWarning`. :attr:`ssl.SSLContext.options` has
1370:data:`~ssl.OP_NO_SSLv2` and :data:`~ssl.OP_NO_SSLv3` set by default and
1371therefore cannot warn about setting the flag again. The
1372:ref:`deprecation section <whatsnew310-deprecated>` has a list of deprecated
1373features.
1374(Contributed by Christian Heimes in :issue:`43880`.)
1375
1376The ssl module now has more secure default settings. Ciphers without forward
1377secrecy or SHA-1 MAC are disabled by default. Security level 2 prohibits
1378weak RSA, DH, and ECC keys with less than 112 bits of security.
1379:class:`~ssl.SSLContext` defaults to minimum protocol version TLS 1.2.
1380Settings are based on Hynek Schlawack's research.
1381(Contributed by Christian Heimes in :issue:`43998`.)
1382
1383The deprecated protocols SSL 3.0, TLS 1.0, and TLS 1.1 are no longer
1384officially supported. Python does not block them actively. However
1385OpenSSL build options, distro configurations, vendor patches, and cipher
1386suites may prevent a successful handshake.
1387
1388Add a *timeout* parameter to the :func:`ssl.get_server_certificate` function.
1389(Contributed by Zackery Spytz in :issue:`31870`.)
1390
1391The ssl module uses heap-types and multi-phase initialization.
1392(Contributed by Christian Heimes in :issue:`42333`.)
1393
1394A new verify flag :const:`~ssl.VERIFY_X509_PARTIAL_CHAIN` has been added.
1395(Contributed by l0x in :issue:`40849`.)
1396
1397sqlite3
1398-------
1399
1400Add audit events for :func:`~sqlite3.connect/handle`,
1401:meth:`~sqlite3.Connection.enable_load_extension`, and
1402:meth:`~sqlite3.Connection.load_extension`.
1403(Contributed by Erlend E. Aasland in :issue:`43762`.)
1404
1405sys
1406---
1407
1408Add :data:`sys.orig_argv` attribute: the list of the original command line
1409arguments passed to the Python executable.
1410(Contributed by Victor Stinner in :issue:`23427`.)
1411
1412Add :data:`sys.stdlib_module_names`, containing the list of the standard library
1413module names.
1414(Contributed by Victor Stinner in :issue:`42955`.)
1415
1416_thread
1417-------
1418
1419:func:`_thread.interrupt_main` now takes an optional signal number to
1420simulate (the default is still :const:`signal.SIGINT`).
1421(Contributed by Antoine Pitrou in :issue:`43356`.)
1422
1423threading
1424---------
1425
1426Add :func:`threading.gettrace` and :func:`threading.getprofile` to
1427retrieve the functions set by :func:`threading.settrace` and
1428:func:`threading.setprofile` respectively.
1429(Contributed by Mario Corchero in :issue:`42251`.)
1430
1431Add :data:`threading.__excepthook__` to allow retrieving the original value
1432of :func:`threading.excepthook` in case it is set to a broken or a different
1433value.
1434(Contributed by Mario Corchero in :issue:`42308`.)
1435
1436traceback
1437---------
1438
1439The :func:`~traceback.format_exception`,
1440:func:`~traceback.format_exception_only`, and
1441:func:`~traceback.print_exception` functions can now take an exception object
1442as a positional-only argument.
1443(Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.)
1444
1445types
1446-----
1447
1448Reintroduce the :data:`types.EllipsisType`, :data:`types.NoneType`
1449and :data:`types.NotImplementedType` classes, providing a new set
1450of types readily interpretable by type checkers.
1451(Contributed by Bas van Beek in :issue:`41810`.)
1452
1453typing
1454------
1455
1456For major changes, see :ref:`new-feat-related-type-hints`.
1457
1458The behavior of :class:`typing.Literal` was changed to conform with :pep:`586`
1459and to match the behavior of static type checkers specified in the PEP.
1460
14611. ``Literal`` now de-duplicates parameters.
14622. Equality comparisons between ``Literal`` objects are now order independent.
14633. ``Literal`` comparisons now respect types.  For example,
1464   ``Literal[0] == Literal[False]`` previously evaluated to ``True``.  It is
1465   now ``False``.  To support this change, the internally used type cache now
1466   supports differentiating types.
14674. ``Literal`` objects will now raise a :exc:`TypeError` exception during
1468   equality comparisons if any of their parameters are not :term:`hashable`.
1469   Note that declaring ``Literal`` with unhashable parameters will not throw
1470   an error::
1471
1472      >>> from typing import Literal
1473      >>> Literal[{0}]
1474      >>> Literal[{0}] == Literal[{False}]
1475      Traceback (most recent call last):
1476        File "<stdin>", line 1, in <module>
1477      TypeError: unhashable type: 'set'
1478
1479(Contributed by Yurii Karabas in :issue:`42345`.)
1480
1481Add new function :func:`typing.is_typeddict` to introspect if an annotation
1482is a :class:`typing.TypedDict`.
1483(Contributed by Patrick Reader in :issue:`41792`.)
1484
1485Subclasses of ``typing.Protocol`` which only have data variables declared
1486will now raise a ``TypeError`` when checked with ``isinstance`` unless they
1487are decorated with :func:`~typing.runtime_checkable`.  Previously, these checks
1488passed silently.  Users should decorate their
1489subclasses with the :func:`!runtime_checkable` decorator
1490if they want runtime protocols.
1491(Contributed by Yurii Karabas in :issue:`38908`.)
1492
1493Importing from the ``typing.io`` and ``typing.re`` submodules will now emit
1494:exc:`DeprecationWarning`.  These submodules have been deprecated since
1495Python 3.8 and will be removed in a future version of Python.  Anything
1496belonging to those submodules should be imported directly from
1497:mod:`typing` instead.
1498(Contributed by Sebastian Rittau in :issue:`38291`.)
1499
1500unittest
1501--------
1502
1503Add new method :meth:`~unittest.TestCase.assertNoLogs` to complement the
1504existing :meth:`~unittest.TestCase.assertLogs`. (Contributed by Kit Yan Choi
1505in :issue:`39385`.)
1506
1507urllib.parse
1508------------
1509
1510Python versions earlier than Python 3.10 allowed using both ``;`` and ``&`` as
1511query parameter separators in :func:`urllib.parse.parse_qs` and
1512:func:`urllib.parse.parse_qsl`.  Due to security concerns, and to conform with
1513newer W3C recommendations, this has been changed to allow only a single
1514separator key, with ``&`` as the default.  This change also affects
1515:func:`!cgi.parse` and :func:`!cgi.parse_multipart` as they use the affected
1516functions internally.  For more details, please see their respective
1517documentation.
1518(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in :issue:`42967`.)
1519
1520The presence of newline or tab characters in parts of a URL allows for some
1521forms of attacks. Following the WHATWG specification that updates :rfc:`3986`,
1522ASCII newline ``\n``, ``\r`` and tab ``\t`` characters are stripped from the
1523URL by the parser in :mod:`urllib.parse` preventing such attacks. The removal
1524characters are controlled by a new module level variable
1525``urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE``. (See :gh:`88048`)
1526
1527xml
1528---
1529
1530Add a :class:`~xml.sax.handler.LexicalHandler` class to the
1531:mod:`xml.sax.handler` module.
1532(Contributed by Jonathan Gossage and Zackery Spytz in :issue:`35018`.)
1533
1534zipimport
1535---------
1536Add methods related to :pep:`451`: :meth:`~zipimport.zipimporter.find_spec`,
1537:meth:`zipimport.zipimporter.create_module`, and
1538:meth:`zipimport.zipimporter.exec_module`.
1539(Contributed by Brett Cannon in :issue:`42131`.)
1540
1541Add :meth:`~zipimport.zipimporter.invalidate_caches` method.
1542(Contributed by Desmond Cheong in :issue:`14678`.)
1543
1544
1545Optimizations
1546=============
1547
1548* Constructors :func:`str`, :func:`bytes` and :func:`bytearray` are now faster
1549  (around 30--40% for small objects).
1550  (Contributed by Serhiy Storchaka in :issue:`41334`.)
1551
1552* The :mod:`runpy` module now imports fewer modules.
1553  The ``python3 -m module-name`` command startup time is 1.4x faster in
1554  average. On Linux, ``python3 -I -m module-name`` imports 69 modules on Python
1555  3.9, whereas it only imports 51 modules (-18) on Python 3.10.
1556  (Contributed by Victor Stinner in :issue:`41006` and :issue:`41718`.)
1557
1558* The ``LOAD_ATTR`` instruction now uses new "per opcode cache" mechanism.  It
1559  is about 36% faster now for regular attributes and 44% faster for slots.
1560  (Contributed by Pablo Galindo and Yury Selivanov in :issue:`42093` and Guido
1561  van Rossum in :issue:`42927`, based on ideas implemented originally in PyPy
1562  and MicroPython.)
1563
1564* When building Python with :option:`--enable-optimizations` now
1565  ``-fno-semantic-interposition`` is added to both the compile and link line.
1566  This speeds builds of the Python interpreter created with :option:`--enable-shared`
1567  with ``gcc`` by up to 30%. See `this article
1568  <https://developers.redhat.com/blog/2020/06/25/red-hat-enterprise-linux-8-2-brings-faster-python-3-8-run-speeds/>`_
1569  for more details. (Contributed by Victor Stinner and Pablo Galindo in
1570  :issue:`38980`.)
1571
1572* Use a new output buffer management code for :mod:`bz2` / :mod:`lzma` /
1573  :mod:`zlib` modules, and add ``.readall()`` function to
1574  ``_compression.DecompressReader`` class. bz2 decompression is now 1.09x ~ 1.17x
1575  faster, lzma decompression 1.20x ~ 1.32x faster, ``GzipFile.read(-1)`` 1.11x
1576  ~ 1.18x faster. (Contributed by Ma Lin, reviewed by Gregory P. Smith, in :issue:`41486`)
1577
1578* When using stringized annotations, annotations dicts for functions are no longer
1579  created when the function is created.  Instead, they are stored as a tuple of
1580  strings, and the function object lazily converts this into the annotations dict
1581  on demand.  This optimization cuts the CPU time needed to define an annotated
1582  function by half.
1583  (Contributed by Yurii Karabas and Inada Naoki in :issue:`42202`.)
1584
1585* Substring search functions such as ``str1 in str2`` and ``str2.find(str1)``
1586  now sometimes use Crochemore & Perrin's "Two-Way" string searching
1587  algorithm to avoid quadratic behavior on long strings.  (Contributed
1588  by Dennis Sweeney in :issue:`41972`)
1589
1590* Add micro-optimizations to ``_PyType_Lookup()`` to improve type attribute cache lookup
1591  performance in the common case of cache hits. This makes the interpreter 1.04 times faster
1592  on average. (Contributed by Dino Viehland in :issue:`43452`.)
1593
1594* The following built-in functions now support the faster :pep:`590` vectorcall calling convention:
1595  :func:`map`, :func:`filter`, :func:`reversed`, :func:`bool` and :func:`float`.
1596  (Contributed by Donghee Na and Jeroen Demeyer in :issue:`43575`, :issue:`43287`, :issue:`41922`, :issue:`41873` and :issue:`41870`.)
1597
1598* :class:`~bz2.BZ2File` performance is improved by removing internal ``RLock``.
1599  This makes :class:`!BZ2File` thread unsafe in the face of multiple simultaneous
1600  readers or writers, just like its equivalent classes in :mod:`gzip` and
1601  :mod:`lzma` have always been.  (Contributed by Inada Naoki in :issue:`43785`.)
1602
1603.. _whatsnew310-deprecated:
1604
1605Deprecated
1606==========
1607
1608* Currently Python accepts numeric literals immediately followed by keywords,
1609  for example ``0in x``, ``1or x``, ``0if 1else 2``.  It allows confusing
1610  and ambiguous expressions like ``[0x1for x in y]`` (which can be
1611  interpreted as ``[0x1 for x in y]`` or ``[0x1f or x in y]``).  Starting in
1612  this release, a deprecation warning is raised if the numeric literal is
1613  immediately followed by one of keywords :keyword:`and`, :keyword:`else`,
1614  :keyword:`for`, :keyword:`if`, :keyword:`in`, :keyword:`is` and :keyword:`or`.
1615  In future releases it will be changed to syntax warning, and finally to
1616  syntax error.
1617  (Contributed by Serhiy Storchaka in :issue:`43833`.)
1618
1619* Starting in this release, there will be a concerted effort to begin
1620  cleaning up old import semantics that were kept for Python 2.7
1621  compatibility. Specifically,
1622  :meth:`!find_loader`/:meth:`!find_module`
1623  (superseded by :meth:`~importlib.abc.MetaPathFinder.find_spec`),
1624  :meth:`~importlib.abc.Loader.load_module`
1625  (superseded by :meth:`~importlib.abc.Loader.exec_module`),
1626  :meth:`!module_repr` (which the import system
1627  takes care of for you), the ``__package__`` attribute
1628  (superseded by ``__spec__.parent``), the ``__loader__`` attribute
1629  (superseded by ``__spec__.loader``), and the ``__cached__`` attribute
1630  (superseded by ``__spec__.cached``) will slowly be removed (as well
1631  as other classes and methods in :mod:`importlib`).
1632  :exc:`ImportWarning` and/or :exc:`DeprecationWarning` will be raised
1633  as appropriate to help identify code which needs updating during
1634  this transition.
1635
1636* The entire ``distutils`` namespace is deprecated, to be removed in
1637  Python 3.12. Refer to the :ref:`module changes <distutils-deprecated>`
1638  section for more information.
1639
1640* Non-integer arguments to :func:`random.randrange` are deprecated.
1641  The :exc:`ValueError` is deprecated in favor of a :exc:`TypeError`.
1642  (Contributed by Serhiy Storchaka and Raymond Hettinger in :issue:`37319`.)
1643
1644* The various ``load_module()`` methods of :mod:`importlib` have been
1645  documented as deprecated since Python 3.6, but will now also trigger
1646  a :exc:`DeprecationWarning`. Use
1647  :meth:`~importlib.abc.Loader.exec_module` instead.
1648  (Contributed by Brett Cannon in :issue:`26131`.)
1649
1650* :meth:`!zimport.zipimporter.load_module` has been deprecated in
1651  preference for :meth:`~zipimport.zipimporter.exec_module`.
1652  (Contributed by Brett Cannon in :issue:`26131`.)
1653
1654* The use of :meth:`~importlib.abc.Loader.load_module` by the import
1655  system now triggers an :exc:`ImportWarning` as
1656  :meth:`~importlib.abc.Loader.exec_module` is preferred.
1657  (Contributed by Brett Cannon in :issue:`26131`.)
1658
1659* The use of :meth:`!importlib.abc.MetaPathFinder.find_module` and
1660  :meth:`!importlib.abc.PathEntryFinder.find_module` by the import system now
1661  trigger an :exc:`ImportWarning` as
1662  :meth:`importlib.abc.MetaPathFinder.find_spec` and
1663  :meth:`importlib.abc.PathEntryFinder.find_spec`
1664  are preferred, respectively. You can use
1665  :func:`importlib.util.spec_from_loader` to help in porting.
1666  (Contributed by Brett Cannon in :issue:`42134`.)
1667
1668* The use of :meth:`!importlib.abc.PathEntryFinder.find_loader` by the import
1669  system now triggers an :exc:`ImportWarning` as
1670  :meth:`importlib.abc.PathEntryFinder.find_spec` is preferred. You can use
1671  :func:`importlib.util.spec_from_loader` to help in porting.
1672  (Contributed by Brett Cannon in :issue:`43672`.)
1673
1674* The various implementations of
1675  :meth:`!importlib.abc.MetaPathFinder.find_module` (
1676  :meth:`!importlib.machinery.BuiltinImporter.find_module`,
1677  :meth:`!importlib.machinery.FrozenImporter.find_module`,
1678  :meth:`!importlib.machinery.WindowsRegistryFinder.find_module`,
1679  :meth:`!importlib.machinery.PathFinder.find_module`,
1680  :meth:`!importlib.abc.MetaPathFinder.find_module` ),
1681  :meth:`!importlib.abc.PathEntryFinder.find_module` (
1682  :meth:`!importlib.machinery.FileFinder.find_module` ), and
1683  :meth:`!importlib.abc.PathEntryFinder.find_loader` (
1684  :meth:`!importlib.machinery.FileFinder.find_loader` )
1685  now raise :exc:`DeprecationWarning` and are slated for removal in
1686  Python 3.12 (previously they were documented as deprecated in Python 3.4).
1687  (Contributed by Brett Cannon in :issue:`42135`.)
1688
1689* :class:`!importlib.abc.Finder` is deprecated (including its sole method,
1690  :meth:`!find_module`). Both
1691  :class:`importlib.abc.MetaPathFinder` and :class:`importlib.abc.PathEntryFinder`
1692  no longer inherit from the class. Users should inherit from one of these two
1693  classes as appropriate instead.
1694  (Contributed by Brett Cannon in :issue:`42135`.)
1695
1696* The deprecations of :mod:`!imp`, :func:`!importlib.find_loader`,
1697  :func:`!importlib.util.set_package_wrapper`,
1698  :func:`!importlib.util.set_loader_wrapper`,
1699  :func:`!importlib.util.module_for_loader`,
1700  :class:`!pkgutil.ImpImporter`, and
1701  :class:`!pkgutil.ImpLoader` have all been updated to list Python 3.12 as the
1702  slated version of removal (they began raising :exc:`DeprecationWarning` in
1703  previous versions of Python).
1704  (Contributed by Brett Cannon in :issue:`43720`.)
1705
1706* The import system now uses the ``__spec__`` attribute on modules before
1707  falling back on :meth:`!module_repr` for a module's
1708  ``__repr__()`` method. Removal of the use of ``module_repr()`` is scheduled
1709  for Python 3.12.
1710  (Contributed by Brett Cannon in :issue:`42137`.)
1711
1712* :meth:`!importlib.abc.Loader.module_repr`,
1713  :meth:`!importlib.machinery.FrozenLoader.module_repr`, and
1714  :meth:`!importlib.machinery.BuiltinLoader.module_repr` are deprecated and
1715  slated for removal in Python 3.12.
1716  (Contributed by Brett Cannon in :issue:`42136`.)
1717
1718* ``sqlite3.OptimizedUnicode`` has been undocumented and obsolete since Python
1719  3.3, when it was made an alias to :class:`str`.  It is now deprecated,
1720  scheduled for removal in Python 3.12.
1721  (Contributed by Erlend E. Aasland in :issue:`42264`.)
1722
1723* The undocumented built-in function ``sqlite3.enable_shared_cache`` is now
1724  deprecated, scheduled for removal in Python 3.12.  Its use is strongly
1725  discouraged by the SQLite3 documentation.  See `the SQLite3 docs
1726  <https://sqlite.org/c3ref/enable_shared_cache.html>`_ for more details.
1727  If a shared cache must be used, open the database in URI mode using the
1728  ``cache=shared`` query parameter.
1729  (Contributed by Erlend E. Aasland in :issue:`24464`.)
1730
1731* The following ``threading`` methods are now deprecated:
1732
1733  * ``threading.currentThread`` => :func:`threading.current_thread`
1734
1735  * ``threading.activeCount`` => :func:`threading.active_count`
1736
1737  * ``threading.Condition.notifyAll`` =>
1738    :meth:`threading.Condition.notify_all`
1739
1740  * ``threading.Event.isSet`` => :meth:`threading.Event.is_set`
1741
1742  * ``threading.Thread.setName`` => :attr:`threading.Thread.name`
1743
1744  * ``threading.thread.getName`` => :attr:`threading.Thread.name`
1745
1746  * ``threading.Thread.isDaemon`` => :attr:`threading.Thread.daemon`
1747
1748  * ``threading.Thread.setDaemon`` => :attr:`threading.Thread.daemon`
1749
1750  (Contributed by Jelle Zijlstra in :gh:`87889`.)
1751
1752* :meth:`!pathlib.Path.link_to` is deprecated and slated for removal in
1753  Python 3.12. Use :meth:`pathlib.Path.hardlink_to` instead.
1754  (Contributed by Barney Gale in :issue:`39950`.)
1755
1756* ``cgi.log()`` is deprecated and slated for removal in Python 3.12.
1757  (Contributed by Inada Naoki in :issue:`41139`.)
1758
1759* The following :mod:`ssl` features have been deprecated since Python 3.6,
1760  Python 3.7, or OpenSSL 1.1.0 and will be removed in 3.11:
1761
1762  * :data:`!OP_NO_SSLv2`, :data:`!OP_NO_SSLv3`, :data:`!OP_NO_TLSv1`,
1763    :data:`!OP_NO_TLSv1_1`, :data:`!OP_NO_TLSv1_2`, and
1764    :data:`!OP_NO_TLSv1_3` are replaced by
1765    :attr:`~ssl.SSLContext.minimum_version` and
1766    :attr:`~ssl.SSLContext.maximum_version`.
1767
1768  * :data:`!PROTOCOL_SSLv2`, :data:`!PROTOCOL_SSLv3`,
1769    :data:`!PROTOCOL_SSLv23`, :data:`!PROTOCOL_TLSv1`,
1770    :data:`!PROTOCOL_TLSv1_1`, :data:`!PROTOCOL_TLSv1_2`, and
1771    :const:`!PROTOCOL_TLS` are deprecated in favor of
1772    :const:`~ssl.PROTOCOL_TLS_CLIENT` and :const:`~ssl.PROTOCOL_TLS_SERVER`
1773
1774  * :func:`!wrap_socket` is replaced by :meth:`ssl.SSLContext.wrap_socket`
1775
1776  * :func:`!match_hostname`
1777
1778  * :func:`!RAND_pseudo_bytes`, :func:`!RAND_egd`
1779
1780  * NPN features like :meth:`ssl.SSLSocket.selected_npn_protocol` and
1781    :meth:`ssl.SSLContext.set_npn_protocols` are replaced by ALPN.
1782
1783* The threading debug (:envvar:`!PYTHONTHREADDEBUG` environment variable) is
1784  deprecated in Python 3.10 and will be removed in Python 3.12. This feature
1785  requires a :ref:`debug build of Python <debug-build>`.
1786  (Contributed by Victor Stinner in :issue:`44584`.)
1787
1788* Importing from the ``typing.io`` and ``typing.re`` submodules will now emit
1789  :exc:`DeprecationWarning`.  These submodules will be removed in a future version
1790  of Python.  Anything belonging to these submodules should be imported directly
1791  from :mod:`typing` instead.
1792  (Contributed by Sebastian Rittau in :issue:`38291`.)
1793
1794.. _whatsnew310-removed:
1795
1796Removed
1797=======
1798
1799* Removed special methods ``__int__``, ``__float__``, ``__floordiv__``,
1800  ``__mod__``, ``__divmod__``, ``__rfloordiv__``, ``__rmod__`` and
1801  ``__rdivmod__`` of the :class:`complex` class.  They always raised
1802  a :exc:`TypeError`.
1803  (Contributed by Serhiy Storchaka in :issue:`41974`.)
1804
1805* The ``ParserBase.error()`` method from the private and undocumented ``_markupbase``
1806  module has been removed.  :class:`html.parser.HTMLParser` is the only subclass of
1807  ``ParserBase`` and its ``error()`` implementation was already removed in
1808  Python 3.5.
1809  (Contributed by Berker Peksag in :issue:`31844`.)
1810
1811* Removed the ``unicodedata.ucnhash_CAPI`` attribute which was an internal
1812  PyCapsule object. The related private ``_PyUnicode_Name_CAPI`` structure was
1813  moved to the internal C API.
1814  (Contributed by Victor Stinner in :issue:`42157`.)
1815
1816* Removed the ``parser`` module, which was deprecated in 3.9 due to the
1817  switch to the new PEG parser, as well as all the C source and header files
1818  that were only being used by the old parser, including ``node.h``, ``parser.h``,
1819  ``graminit.h`` and ``grammar.h``.
1820
1821* Removed the Public C API functions ``PyParser_SimpleParseStringFlags``,
1822  ``PyParser_SimpleParseStringFlagsFilename``,
1823  ``PyParser_SimpleParseFileFlags`` and ``PyNode_Compile``
1824  that were deprecated in 3.9 due to the switch to the new PEG parser.
1825
1826* Removed the ``formatter`` module, which was deprecated in Python 3.4.
1827  It is somewhat obsolete, little used, and not tested. It was originally
1828  scheduled to be removed in Python 3.6, but such removals were delayed until
1829  after Python 2.7 EOL. Existing users should copy whatever classes they use
1830  into their code.
1831  (Contributed by Donghee Na and Terry J. Reedy in :issue:`42299`.)
1832
1833* Removed the :c:func:`!PyModule_GetWarningsModule` function that was useless
1834  now due to the :mod:`!_warnings` module was converted to a builtin module in 2.6.
1835  (Contributed by Hai Shi in :issue:`42599`.)
1836
1837* Remove deprecated aliases to :ref:`collections-abstract-base-classes` from
1838  the :mod:`collections` module.
1839  (Contributed by Victor Stinner in :issue:`37324`.)
1840
1841* The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's
1842  :doc:`high-level API <../library/asyncio-api-index>` following deprecation
1843  in Python 3.8.  The motivation behind this change is multifold:
1844
1845  1. This simplifies the high-level API.
1846  2. The functions in the high-level API have been implicitly getting the
1847     current thread's running event loop since Python 3.7.  There isn't a need to
1848     pass the event loop to the API in most normal use cases.
1849  3. Event loop passing is error-prone especially when dealing with loops
1850     running in different threads.
1851
1852  Note that the low-level API will still accept ``loop``.
1853  See :ref:`changes-python-api` for examples of how to replace existing code.
1854
1855  (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
1856  in :issue:`42392`.)
1857
1858
1859Porting to Python 3.10
1860======================
1861
1862This section lists previously described changes and other bugfixes
1863that may require changes to your code.
1864
1865
1866Changes in the Python syntax
1867----------------------------
1868
1869* Deprecation warning is now emitted when compiling previously valid syntax
1870  if the numeric literal is immediately followed by a keyword (like in ``0in x``).
1871  In future releases it will be changed to syntax warning, and finally to a
1872  syntax error.  To get rid of the warning and make the code compatible with
1873  future releases just add a space between the numeric literal and the
1874  following keyword.
1875  (Contributed by Serhiy Storchaka in :issue:`43833`.)
1876
1877.. _changes-python-api:
1878
1879Changes in the Python API
1880-------------------------
1881
1882* The *etype* parameters of the :func:`~traceback.format_exception`,
1883  :func:`~traceback.format_exception_only`, and
1884  :func:`~traceback.print_exception` functions in the :mod:`traceback` module
1885  have been renamed to *exc*.
1886  (Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.)
1887
1888* :mod:`atexit`: At Python exit, if a callback registered with
1889  :func:`atexit.register` fails, its exception is now logged. Previously, only
1890  some exceptions were logged, and the last exception was always silently
1891  ignored.
1892  (Contributed by Victor Stinner in :issue:`42639`.)
1893
1894* :class:`collections.abc.Callable` generic now flattens type parameters, similar
1895  to what :data:`typing.Callable` currently does.  This means that
1896  ``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
1897  ``(int, str, str)``; previously this was ``([int, str], str)``.  Code which
1898  accesses the arguments via :func:`typing.get_args` or ``__args__`` need to account
1899  for this change.  Furthermore, :exc:`TypeError` may be raised for invalid forms
1900  of parameterizing :class:`collections.abc.Callable` which may have passed
1901  silently in Python 3.9.
1902  (Contributed by Ken Jin in :issue:`42195`.)
1903
1904* :meth:`socket.htons` and :meth:`socket.ntohs` now raise :exc:`OverflowError`
1905  instead of :exc:`DeprecationWarning` if the given parameter will not fit in
1906  a 16-bit unsigned integer.
1907  (Contributed by Erlend E. Aasland in :issue:`42393`.)
1908
1909* The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's
1910  :doc:`high-level API <../library/asyncio-api-index>` following deprecation
1911  in Python 3.8.
1912
1913  A coroutine that currently looks like this::
1914
1915     async def foo(loop):
1916         await asyncio.sleep(1, loop=loop)
1917
1918  Should be replaced with this::
1919
1920     async def foo():
1921         await asyncio.sleep(1)
1922
1923  If ``foo()`` was specifically designed *not* to run in the current thread's
1924  running event loop (e.g. running in another thread's event loop), consider
1925  using :func:`asyncio.run_coroutine_threadsafe` instead.
1926
1927  (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
1928  in :issue:`42392`.)
1929
1930* The :data:`types.FunctionType` constructor now inherits the current builtins
1931  if the *globals* dictionary has no ``"__builtins__"`` key, rather than using
1932  ``{"None": None}`` as builtins: same behavior as :func:`eval` and
1933  :func:`exec` functions.  Defining a function with ``def function(...): ...``
1934  in Python is not affected, globals cannot be overridden with this syntax: it
1935  also inherits the current builtins.
1936  (Contributed by Victor Stinner in :issue:`42990`.)
1937
1938Changes in the C API
1939--------------------
1940
1941* The C API functions ``PyParser_SimpleParseStringFlags``,
1942  ``PyParser_SimpleParseStringFlagsFilename``,
1943  ``PyParser_SimpleParseFileFlags``, ``PyNode_Compile`` and the type
1944  used by these functions, ``struct _node``, were removed due to the switch
1945  to the new PEG parser.
1946
1947  Source should be now be compiled directly to a code object using, for
1948  example, :c:func:`Py_CompileString`. The resulting code object can then be
1949  evaluated using, for example, :c:func:`PyEval_EvalCode`.
1950
1951  Specifically:
1952
1953  * A call to ``PyParser_SimpleParseStringFlags`` followed by
1954    ``PyNode_Compile`` can be replaced by calling :c:func:`Py_CompileString`.
1955
1956  * There is no direct replacement for ``PyParser_SimpleParseFileFlags``.
1957    To compile code from a ``FILE *`` argument, you will need to read
1958    the file in C and pass the resulting buffer to :c:func:`Py_CompileString`.
1959
1960  * To compile a file given a ``char *`` filename, explicitly open the file, read
1961    it and compile the result. One way to do this is using the :py:mod:`io`
1962    module with :c:func:`PyImport_ImportModule`, :c:func:`PyObject_CallMethod`,
1963    :c:func:`PyBytes_AsString` and :c:func:`Py_CompileString`,
1964    as sketched below. (Declarations and error handling are omitted.) ::
1965
1966       io_module = Import_ImportModule("io");
1967       fileobject = PyObject_CallMethod(io_module, "open", "ss", filename, "rb");
1968       source_bytes_object = PyObject_CallMethod(fileobject, "read", "");
1969       result = PyObject_CallMethod(fileobject, "close", "");
1970       source_buf = PyBytes_AsString(source_bytes_object);
1971       code = Py_CompileString(source_buf, filename, Py_file_input);
1972
1973  * For ``FrameObject`` objects, the :attr:`~frame.f_lasti` member now represents a wordcode
1974    offset instead of a simple offset into the bytecode string. This means that this
1975    number needs to be multiplied by 2 to be used with APIs that expect a byte offset
1976    instead (like :c:func:`PyCode_Addr2Line` for example). Notice as well that the
1977    :attr:`!f_lasti` member of ``FrameObject`` objects is not considered stable: please
1978    use :c:func:`PyFrame_GetLineNumber` instead.
1979
1980CPython bytecode changes
1981========================
1982
1983* The ``MAKE_FUNCTION`` instruction now accepts either a dict or a tuple of
1984  strings as the function's annotations.
1985  (Contributed by Yurii Karabas and Inada Naoki in :issue:`42202`.)
1986
1987Build Changes
1988=============
1989
1990* :pep:`644`: Python now requires OpenSSL 1.1.1 or newer. OpenSSL 1.0.2 is no
1991  longer supported.
1992  (Contributed by Christian Heimes in :issue:`43669`.)
1993
1994* The C99 functions :c:func:`snprintf` and :c:func:`vsnprintf` are now required
1995  to build Python.
1996  (Contributed by Victor Stinner in :issue:`36020`.)
1997
1998* :mod:`sqlite3` requires SQLite 3.7.15 or higher. (Contributed by Sergey Fedoseev
1999  and Erlend E. Aasland in :issue:`40744` and :issue:`40810`.)
2000
2001* The :mod:`atexit` module must now always be built as a built-in module.
2002  (Contributed by Victor Stinner in :issue:`42639`.)
2003
2004* Add :option:`--disable-test-modules` option to the ``configure`` script:
2005  don't build nor install test modules.
2006  (Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in :issue:`27640`.)
2007
2008* Add :option:`--with-wheel-pkg-dir=PATH option <--with-wheel-pkg-dir>`
2009  to the ``./configure`` script. If
2010  specified, the :mod:`ensurepip` module looks for ``setuptools`` and ``pip``
2011  wheel packages in this directory: if both are present, these wheel packages
2012  are used instead of ensurepip bundled wheel packages.
2013
2014  Some Linux distribution packaging policies recommend against bundling
2015  dependencies. For example, Fedora installs wheel packages in the
2016  ``/usr/share/python-wheels/`` directory and don't install the
2017  ``ensurepip._bundled`` package.
2018
2019  (Contributed by Victor Stinner in :issue:`42856`.)
2020
2021* Add a new :option:`configure --without-static-libpython option
2022  <--without-static-libpython>` to not build the ``libpythonMAJOR.MINOR.a``
2023  static library and not install the ``python.o`` object file.
2024
2025  (Contributed by Victor Stinner in :issue:`43103`.)
2026
2027* The ``configure`` script now uses the ``pkg-config`` utility, if available,
2028  to detect the location of Tcl/Tk headers and libraries.  As before, those
2029  locations can be explicitly specified with the ``--with-tcltk-includes``
2030  and ``--with-tcltk-libs`` configuration options.
2031  (Contributed by Manolis Stamatogiannakis in :issue:`42603`.)
2032
2033* Add :option:`--with-openssl-rpath` option to ``configure`` script. The option
2034  simplifies building Python with a custom OpenSSL installation, e.g.
2035  ``./configure --with-openssl=/path/to/openssl --with-openssl-rpath=auto``.
2036  (Contributed by Christian Heimes in :issue:`43466`.)
2037
2038
2039C API Changes
2040=============
2041
2042PEP 652: Maintaining the Stable ABI
2043-----------------------------------
2044
2045The Stable ABI (Application Binary Interface) for extension modules or
2046embedding Python is now explicitly defined.
2047:ref:`stable` describes C API and ABI stability guarantees along with best
2048practices for using the Stable ABI.
2049
2050(Contributed by Petr Viktorin in :pep:`652` and :issue:`43795`.)
2051
2052New Features
2053------------
2054
2055* The result of :c:func:`PyNumber_Index` now always has exact type :class:`int`.
2056  Previously, the result could have been an instance of a subclass of ``int``.
2057  (Contributed by Serhiy Storchaka in :issue:`40792`.)
2058
2059* Add a new :c:member:`~PyConfig.orig_argv` member to the :c:type:`PyConfig`
2060  structure: the list of the original command line arguments passed to the
2061  Python executable.
2062  (Contributed by Victor Stinner in :issue:`23427`.)
2063
2064* The :c:func:`PyDateTime_DATE_GET_TZINFO` and
2065  :c:func:`PyDateTime_TIME_GET_TZINFO` macros have been added for accessing
2066  the ``tzinfo`` attributes of :class:`datetime.datetime` and
2067  :class:`datetime.time` objects.
2068  (Contributed by Zackery Spytz in :issue:`30155`.)
2069
2070* Add a :c:func:`PyCodec_Unregister` function to unregister a codec
2071  search function.
2072  (Contributed by Hai Shi in :issue:`41842`.)
2073
2074* The :c:func:`PyIter_Send` function was added to allow
2075  sending value into iterator without raising ``StopIteration`` exception.
2076  (Contributed by Vladimir Matveev in :issue:`41756`.)
2077
2078* Add :c:func:`PyUnicode_AsUTF8AndSize` to the limited C API.
2079  (Contributed by Alex Gaynor in :issue:`41784`.)
2080
2081* Add :c:func:`PyModule_AddObjectRef` function: similar to
2082  :c:func:`PyModule_AddObject` but don't steal a reference to the value on
2083  success.
2084  (Contributed by Victor Stinner in :issue:`1635741`.)
2085
2086* Add :c:func:`Py_NewRef` and :c:func:`Py_XNewRef` functions to increment the
2087  reference count of an object and return the object.
2088  (Contributed by Victor Stinner in :issue:`42262`.)
2089
2090* The :c:func:`PyType_FromSpecWithBases` and :c:func:`PyType_FromModuleAndSpec`
2091  functions now accept a single class as the *bases* argument.
2092  (Contributed by Serhiy Storchaka in :issue:`42423`.)
2093
2094* The :c:func:`PyType_FromModuleAndSpec` function now accepts NULL ``tp_doc``
2095  slot.
2096  (Contributed by Hai Shi in :issue:`41832`.)
2097
2098* The :c:func:`PyType_GetSlot` function can accept
2099  :ref:`static types <static-types>`.
2100  (Contributed by Hai Shi and Petr Viktorin in :issue:`41073`.)
2101
2102* Add a new :c:func:`PySet_CheckExact` function to the C-API to check if an
2103  object is an instance of :class:`set` but not an instance of a subtype.
2104  (Contributed by Pablo Galindo in :issue:`43277`.)
2105
2106* Add :c:func:`PyErr_SetInterruptEx` which allows passing a signal number
2107  to simulate.
2108  (Contributed by Antoine Pitrou in :issue:`43356`.)
2109
2110* The limited C API is now supported if :ref:`Python is built in debug mode
2111  <debug-build>` (if the ``Py_DEBUG`` macro is defined). In the limited C API,
2112  the :c:func:`Py_INCREF` and :c:func:`Py_DECREF` functions are now implemented
2113  as opaque function
2114  calls, rather than accessing directly the :c:member:`PyObject.ob_refcnt`
2115  member, if Python is built in debug mode and the ``Py_LIMITED_API`` macro
2116  targets Python 3.10 or newer. It became possible to support the limited C API
2117  in debug mode because the :c:type:`PyObject` structure is the same in release
2118  and debug mode since Python 3.8 (see :issue:`36465`).
2119
2120  The limited C API is still not supported in the :option:`--with-trace-refs`
2121  special build (``Py_TRACE_REFS`` macro).
2122  (Contributed by Victor Stinner in :issue:`43688`.)
2123
2124* Add the :c:func:`Py_Is(x, y) <Py_Is>` function to test if the *x* object is
2125  the *y* object, the same as ``x is y`` in Python. Add also the
2126  :c:func:`Py_IsNone`, :c:func:`Py_IsTrue`, :c:func:`Py_IsFalse` functions to
2127  test if an object is, respectively, the ``None`` singleton, the ``True``
2128  singleton or the ``False`` singleton.
2129  (Contributed by Victor Stinner in :issue:`43753`.)
2130
2131* Add new functions to control the garbage collector from C code:
2132  :c:func:`PyGC_Enable()`,
2133  :c:func:`PyGC_Disable()`,
2134  :c:func:`PyGC_IsEnabled()`.
2135  These functions allow to activate, deactivate and query the state of the garbage collector from C code without
2136  having to import the :mod:`gc` module.
2137
2138* Add a new :c:macro:`Py_TPFLAGS_DISALLOW_INSTANTIATION` type flag to disallow
2139  creating type instances.
2140  (Contributed by Victor Stinner in :issue:`43916`.)
2141
2142* Add a new :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag for creating immutable
2143  type objects: type attributes cannot be set nor deleted.
2144  (Contributed by Victor Stinner and Erlend E. Aasland in :issue:`43908`.)
2145
2146Porting to Python 3.10
2147----------------------
2148
2149* The ``PY_SSIZE_T_CLEAN`` macro must now be defined to use
2150  :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` formats which use
2151  ``#``: ``es#``, ``et#``, ``s#``, ``u#``, ``y#``, ``z#``, ``U#`` and ``Z#``.
2152  See :ref:`arg-parsing` and :pep:`353`.
2153  (Contributed by Victor Stinner in :issue:`40943`.)
2154
2155* Since :c:func:`Py_REFCNT()` is changed to the inline static function,
2156  ``Py_REFCNT(obj) = new_refcnt`` must be replaced with ``Py_SET_REFCNT(obj, new_refcnt)``:
2157  see :c:func:`Py_SET_REFCNT()` (available since Python 3.9). For backward
2158  compatibility, this macro can be used::
2159
2160      #if PY_VERSION_HEX < 0x030900A4
2161      #  define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0)
2162      #endif
2163
2164  (Contributed by Victor Stinner in :issue:`39573`.)
2165
2166* Calling :c:func:`PyDict_GetItem` without :term:`GIL` held had been allowed
2167  for historical reason. It is no longer allowed.
2168  (Contributed by Victor Stinner in :issue:`40839`.)
2169
2170* ``PyUnicode_FromUnicode(NULL, size)`` and ``PyUnicode_FromStringAndSize(NULL, size)``
2171  raise ``DeprecationWarning`` now.  Use :c:func:`PyUnicode_New` to allocate
2172  Unicode object without initial data.
2173  (Contributed by Inada Naoki in :issue:`36346`.)
2174
2175* The private ``_PyUnicode_Name_CAPI`` structure of the PyCapsule API
2176  ``unicodedata.ucnhash_CAPI`` has been moved to the internal C API.
2177  (Contributed by Victor Stinner in :issue:`42157`.)
2178
2179* :c:func:`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
2180  :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome` and
2181  :c:func:`Py_GetProgramName` functions now return ``NULL`` if called before
2182  :c:func:`Py_Initialize` (before Python is initialized). Use the new
2183  :ref:`init-config` API to get the :ref:`init-path-config`.
2184  (Contributed by Victor Stinner in :issue:`42260`.)
2185
2186* :c:func:`PyList_SET_ITEM`, :c:func:`PyTuple_SET_ITEM` and
2187  :c:func:`PyCell_SET` macros can no longer be used as l-value or r-value.
2188  For example, ``x = PyList_SET_ITEM(a, b, c)`` and
2189  ``PyList_SET_ITEM(a, b, c) = x`` now fail with a compiler error. It prevents
2190  bugs like ``if (PyList_SET_ITEM (a, b, c) < 0) ...`` test.
2191  (Contributed by Zackery Spytz and Victor Stinner in :issue:`30459`.)
2192
2193* The non-limited API files ``odictobject.h``, ``parser_interface.h``,
2194  ``picklebufobject.h``, ``pyarena.h``, ``pyctype.h``, ``pydebug.h``,
2195  ``pyfpe.h``, and ``pytime.h`` have been moved to the ``Include/cpython``
2196  directory. These files must not be included directly, as they are already
2197  included in ``Python.h``; see :ref:`api-includes`. If they have
2198  been included directly, consider including ``Python.h`` instead.
2199  (Contributed by Nicholas Sim in :issue:`35134`.)
2200
2201* Use the :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` type flag to create immutable type
2202  objects. Do not rely on :c:macro:`Py_TPFLAGS_HEAPTYPE` to decide if a type
2203  object is mutable or not; check if :c:macro:`Py_TPFLAGS_IMMUTABLETYPE` is set
2204  instead.
2205  (Contributed by Victor Stinner and Erlend E. Aasland in :issue:`43908`.)
2206
2207* The undocumented function ``Py_FrozenMain`` has been removed from the
2208  limited API. The function is mainly useful for custom builds of Python.
2209  (Contributed by Petr Viktorin in :issue:`26241`.)
2210
2211Deprecated
2212----------
2213
2214* The ``PyUnicode_InternImmortal()`` function is now deprecated
2215  and will be removed in Python 3.12: use :c:func:`PyUnicode_InternInPlace`
2216  instead.
2217  (Contributed by Victor Stinner in :issue:`41692`.)
2218
2219Removed
2220-------
2221
2222* Removed ``Py_UNICODE_str*`` functions manipulating ``Py_UNICODE*`` strings.
2223  (Contributed by Inada Naoki in :issue:`41123`.)
2224
2225  * ``Py_UNICODE_strlen``: use :c:func:`PyUnicode_GetLength` or
2226    :c:macro:`PyUnicode_GET_LENGTH`
2227  * ``Py_UNICODE_strcat``: use :c:func:`PyUnicode_CopyCharacters` or
2228    :c:func:`PyUnicode_FromFormat`
2229  * ``Py_UNICODE_strcpy``, ``Py_UNICODE_strncpy``: use
2230    :c:func:`PyUnicode_CopyCharacters` or :c:func:`PyUnicode_Substring`
2231  * ``Py_UNICODE_strcmp``: use :c:func:`PyUnicode_Compare`
2232  * ``Py_UNICODE_strncmp``: use :c:func:`PyUnicode_Tailmatch`
2233  * ``Py_UNICODE_strchr``, ``Py_UNICODE_strrchr``: use
2234    :c:func:`PyUnicode_FindChar`
2235
2236* Removed ``PyUnicode_GetMax()``. Please migrate to new (:pep:`393`) APIs.
2237  (Contributed by Inada Naoki in :issue:`41103`.)
2238
2239* Removed ``PyLong_FromUnicode()``. Please migrate to :c:func:`PyLong_FromUnicodeObject`.
2240  (Contributed by Inada Naoki in :issue:`41103`.)
2241
2242* Removed ``PyUnicode_AsUnicodeCopy()``. Please use :c:func:`PyUnicode_AsUCS4Copy` or
2243  :c:func:`PyUnicode_AsWideCharString`
2244  (Contributed by Inada Naoki in :issue:`41103`.)
2245
2246* Removed ``_Py_CheckRecursionLimit`` variable: it has been replaced by
2247  ``ceval.recursion_limit`` of the :c:type:`PyInterpreterState` structure.
2248  (Contributed by Victor Stinner in :issue:`41834`.)
2249
2250* Removed undocumented macros ``Py_ALLOW_RECURSION`` and
2251  ``Py_END_ALLOW_RECURSION`` and the ``recursion_critical`` field of the
2252  :c:type:`PyInterpreterState` structure.
2253  (Contributed by Serhiy Storchaka in :issue:`41936`.)
2254
2255* Removed the undocumented ``PyOS_InitInterrupts()`` function. Initializing
2256  Python already implicitly installs signal handlers: see
2257  :c:member:`PyConfig.install_signal_handlers`.
2258  (Contributed by Victor Stinner in :issue:`41713`.)
2259
2260* Remove the ``PyAST_Validate()`` function. It is no longer possible to build a
2261  AST object (``mod_ty`` type) with the public C API. The function was already
2262  excluded from the limited C API (:pep:`384`).
2263  (Contributed by Victor Stinner in :issue:`43244`.)
2264
2265* Remove the ``symtable.h`` header file and the undocumented functions:
2266
2267  * ``PyST_GetScope()``
2268  * ``PySymtable_Build()``
2269  * ``PySymtable_BuildObject()``
2270  * ``PySymtable_Free()``
2271  * ``Py_SymtableString()``
2272  * ``Py_SymtableStringObject()``
2273
2274  The ``Py_SymtableString()`` function was part the stable ABI by mistake but
2275  it could not be used, because the ``symtable.h`` header file was excluded
2276  from the limited C API.
2277
2278  Use Python :mod:`symtable` module instead.
2279  (Contributed by Victor Stinner in :issue:`43244`.)
2280
2281* Remove :c:func:`PyOS_ReadlineFunctionPointer` from the limited C API headers
2282  and from ``python3.dll``, the library that provides the stable ABI on
2283  Windows. Since the function takes a ``FILE*`` argument, its ABI stability
2284  cannot be guaranteed.
2285  (Contributed by Petr Viktorin in :issue:`43868`.)
2286
2287* Remove ``ast.h``, ``asdl.h``, and ``Python-ast.h`` header files.
2288  These functions were undocumented and excluded from the limited C API.
2289  Most names defined by these header files were not prefixed by ``Py`` and so
2290  could create names conflicts. For example, ``Python-ast.h`` defined a
2291  ``Yield`` macro which was conflict with the ``Yield`` name used by the
2292  Windows ``<winbase.h>`` header. Use the Python :mod:`ast` module instead.
2293  (Contributed by Victor Stinner in :issue:`43244`.)
2294
2295* Remove the compiler and parser functions using ``struct _mod`` type, because
2296  the public AST C API was removed:
2297
2298  * ``PyAST_Compile()``
2299  * ``PyAST_CompileEx()``
2300  * ``PyAST_CompileObject()``
2301  * ``PyFuture_FromAST()``
2302  * ``PyFuture_FromASTObject()``
2303  * ``PyParser_ASTFromFile()``
2304  * ``PyParser_ASTFromFileObject()``
2305  * ``PyParser_ASTFromFilename()``
2306  * ``PyParser_ASTFromString()``
2307  * ``PyParser_ASTFromStringObject()``
2308
2309  These functions were undocumented and excluded from the limited C API.
2310  (Contributed by Victor Stinner in :issue:`43244`.)
2311
2312* Remove the ``pyarena.h`` header file with functions:
2313
2314  * ``PyArena_New()``
2315  * ``PyArena_Free()``
2316  * ``PyArena_Malloc()``
2317  * ``PyArena_AddPyObject()``
2318
2319  These functions were undocumented, excluded from the limited C API, and were
2320  only used internally by the compiler.
2321  (Contributed by Victor Stinner in :issue:`43244`.)
2322
2323* The ``PyThreadState.use_tracing`` member has been removed to optimize Python.
2324  (Contributed by Mark Shannon in :issue:`43760`.)
2325
2326
2327Notable security feature in 3.10.7
2328==================================
2329
2330Converting between :class:`int` and :class:`str` in bases other than 2
2331(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)
2332now raises a :exc:`ValueError` if the number of digits in string form is
2333above a limit to avoid potential denial of service attacks due to the
2334algorithmic complexity. This is a mitigation for :cve:`2020-10735`.
2335This limit can be configured or disabled by environment variable, command
2336line flag, or :mod:`sys` APIs. See the :ref:`integer string conversion
2337length limitation <int_max_str_digits>` documentation.  The default limit
2338is 4300 digits in string form.
2339
2340Notable security feature in 3.10.8
2341==================================
2342
2343The deprecated :mod:`!mailcap` module now refuses to inject unsafe text
2344(filenames, MIME types, parameters) into shell commands. Instead of using such
2345text, it will warn and act as if a match was not found (or for test commands,
2346as if the test failed).
2347(Contributed by Petr Viktorin in :gh:`98966`.)
2348
2349Notable changes in 3.10.12
2350==========================
2351
2352tarfile
2353-------
2354
2355* The extraction methods in :mod:`tarfile`, and :func:`shutil.unpack_archive`,
2356  have a new a *filter* argument that allows limiting tar features than may be
2357  surprising or dangerous, such as creating files outside the destination
2358  directory.
2359  See :ref:`tarfile-extraction-filter` for details.
2360  In Python 3.12, use without the *filter* argument will show a
2361  :exc:`DeprecationWarning`.
2362  In Python 3.14, the default will switch to ``'data'``.
2363  (Contributed by Petr Viktorin in :pep:`706`.)
2364