blob: 6623adfbf4f3d32ef5925801863c3e8d65a57c2b [file] [log] [blame]
Pablo Galindod4fe0982020-05-19 03:33:01 +01001****************************
2 What's New In Python 3.10
3****************************
4
5:Release: |release|
6:Date: |today|
7
8.. Rules for maintenance:
9
10 * Anyone can add text to this document. Do not spend very much time
11 on the wording of your changes, because your text will probably
12 get rewritten to some degree.
13
14 * The maintainer will go through Misc/NEWS periodically and add
15 changes; it's therefore more important to add your changes to
16 Misc/NEWS than to this file.
17
18 * This is not a complete list of every single change; completeness
19 is the purpose of Misc/NEWS. Some changes I consider too small
20 or esoteric to include. If such a change is added to the text,
21 I'll just remove it. (This is another reason you shouldn't spend
22 too much time on writing your addition.)
23
24 * If you want to draw your new text to the attention of the
25 maintainer, add 'XXX' to the beginning of the paragraph or
26 section.
27
28 * It's OK to just add a fragmentary note about a change. For
29 example: "XXX Describe the transmogrify() function added to the
30 socket module." The maintainer will research the change and
31 write the necessary text.
32
33 * You can comment out your additions if you like, but it's not
34 necessary (especially when a final release is some months away).
35
36 * Credit the author of a patch or bugfix. Just the name is
37 sufficient; the e-mail address isn't necessary.
38
39 * It's helpful to add the bug/patch number as a comment:
40
41 XXX Describe the transmogrify() function added to the socket
42 module.
43 (Contributed by P.Y. Developer in :issue:`12345`.)
44
45 This saves the maintainer the effort of going through the Mercurial log
46 when researching a change.
47
48This article explains the new features in Python 3.10, compared to 3.9.
49
Ned Deily29251b72020-05-19 07:39:29 -040050For full details, see the :ref:`changelog <changelog>`.
Pablo Galindod4fe0982020-05-19 03:33:01 +010051
52.. note::
53
54 Prerelease users should be aware that this document is currently in draft
55 form. It will be updated substantially as Python 3.10 moves towards release,
56 so it's worth checking back even after reading earlier versions.
57
58
59Summary -- Release highlights
60=============================
61
62.. This section singles out the most important changes in Python 3.10.
63 Brevity is key.
64
65
66.. PEP-sized items next.
67
68
69
70New Features
71============
72
Batuhan Taskaya044a1042020-10-06 23:03:02 +030073.. _whatsnew310-pep563:
74
Pablo Galindo7c8e0b02021-01-25 23:15:51 +000075Parenthesized context managers
76------------------------------
77
78Using enclosing parentheses for continuation across multiple lines
79in context managers is now supported. This allows formatting a long
80collection of context managers in multiple lines in a similar way
81as it was previously possible with import statements. For instance,
82all these examples are now valid:
83
84.. code-block:: python
85
86 with (CtxManager() as example):
87 ...
88
89 with (
90 CtxManager1(),
91 CtxManager2()
92 ):
93 ...
94
95 with (CtxManager1() as example,
96 CtxManager2()):
97 ...
98
99 with (CtxManager1(),
100 CtxManager2() as example):
101 ...
102
103 with (
104 CtxManager1() as example1,
105 CtxManager2() as example2
106 ):
107 ...
108
109it is also possible to use a trailing comma at the end of the
110enclosed group:
111
112.. code-block:: python
113
114 with (
115 CtxManager1() as example1,
116 CtxManager2() as example2,
117 CtxManager3() as example3,
118 ):
119 ...
120
121This new syntax uses the non LL(1) capacities of the new parser.
122Check :pep:`617` for more details.
123
124(Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou
125in :issue:`12782` and :issue:`40334`.)
126
127
Pablo Galindo37494b42021-04-14 02:36:07 +0100128Better error messages
129---------------------
130
131SyntaxErrors
132~~~~~~~~~~~~
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300133
Ken Jin727a68b2021-03-03 08:52:03 +0800134When parsing code that contains unclosed parentheses or brackets the interpreter
135now includes the location of the unclosed bracket of parentheses instead of displaying
136*SyntaxError: unexpected EOF while parsing* or pointing to some incorrect location.
137For instance, consider the following code (notice the unclosed '{'):
Batuhan Taskaya044a1042020-10-06 23:03:02 +0300138
Ken Jin727a68b2021-03-03 08:52:03 +0800139.. code-block:: python
Pablo Galindod4fe0982020-05-19 03:33:01 +0100140
Ken Jin727a68b2021-03-03 08:52:03 +0800141 expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
142 38: 4, 39: 4, 45: 5, 46: 5, 47: 5, 48: 5, 49: 5, 54: 6,
143 some_other_code = foo()
Dennis Sweeney3ee0e482020-06-12 13:19:25 -0400144
Ken Jin727a68b2021-03-03 08:52:03 +0800145previous versions of the interpreter reported confusing places as the location of
146the syntax error:
Ram Rachum59cf8532020-06-19 23:39:22 +0300147
Pablo Galindoff3d9c02021-04-16 01:28:48 +0100148.. code-block:: python
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300149
Ken Jin727a68b2021-03-03 08:52:03 +0800150 File "example.py", line 3
151 some_other_code = foo()
152 ^
153 SyntaxError: invalid syntax
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300154
Ken Jin727a68b2021-03-03 08:52:03 +0800155but in Python3.10 a more informative error is emitted:
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300156
Pablo Galindoff3d9c02021-04-16 01:28:48 +0100157.. code-block:: python
Mikhail Golubev4f3c2502020-10-08 00:44:31 +0300158
Ken Jin727a68b2021-03-03 08:52:03 +0800159 File "example.py", line 1
160 expected = {9: 1, 18: 2, 19: 2, 27: 3, 28: 3, 29: 3, 36: 4, 37: 4,
161 ^
162 SyntaxError: '{' was never closed
Fidget-Spinner8e1dd552020-10-05 12:40:52 +0800163
164
Ken Jin727a68b2021-03-03 08:52:03 +0800165In a similar way, errors involving unclosed string literals (single and triple
166quoted) now point to the start of the string instead of reporting EOF/EOL.
Fidget-Spinner8e1dd552020-10-05 12:40:52 +0800167
Ken Jin727a68b2021-03-03 08:52:03 +0800168These improvements are inspired by previous work in the PyPy interpreter.
Fidget-Spinner8e1dd552020-10-05 12:40:52 +0800169
Ken Jin727a68b2021-03-03 08:52:03 +0800170(Contributed by Pablo Galindo in :issue:`42864` and Batuhan Taskaya in
171:issue:`40176`.)
Fidget-Spinner8e1dd552020-10-05 12:40:52 +0800172
Pablo Galindoff3d9c02021-04-16 01:28:48 +0100173A considerable ammount of new specialized messages for :exc:`SyntaxError` exceptions
174have been incorporated. Some of the most notable ones:
175
176* Missing ``:`` before blocks:
177
178.. code-block:: python
179
180 >>> if rocket.position > event_horizon
181 File "<stdin>", line 1
182 if rocket.position > event_horizon
183 ^
184 SyntaxError: expected ':'
185
186
187* Unparenthesised tuples in comprehensions targets:
188
189.. code-block:: python
190
191 >>> {x,y for x,y in range(100)}
192 File "<stdin>", line 1
193 {x,y for x,y in range(100)}
194 ^
195 SyntaxError: did you forget parentheses around the comprehension target?
196
197* Missing commas in collection literals:
198
199.. code-block:: python
200
201 >>> items = {
202 ... x: 1,
203 ... y: 2
204 ... z: 3,
205 File "<stdin>", line 3
206 y: 2
207 ^
208 SyntaxError: invalid syntax. Perhaps you forgot a comma?
209
210* Exception groups without parentheses:
211
212.. code-block:: python
213
214 >>> try:
215 ... build_dyson_sphere()
216 ... except NotEnoughScienceError, NotEnoughResourcesError:
217 File "<stdin>", line 3
218 except NotEnoughScienceError, NotEnoughResourcesError:
219 ^
220 SyntaxError: exception group must be parenthesized
221
222* Missing ``:`` and values in dictionary literals:
223
224.. code-block:: python
225
226 >>> values = {
227 ... x: 1,
228 ... y: 2,
229 ... z:
230 ... }
231 File "<stdin>", line 4
232 z:
233 ^
234 SyntaxError: expression expected after dictionary key and ':'
235
236 >>> values = {x:1, y:2, z w:3}
237 File "<stdin>", line 1
238 values = {x:1, y:2, z w:3}
239 ^
240 SyntaxError: ':' expected after dictionary key
241
242* Usage of ``=`` instead of ``==`` in comparisons:
243
244.. code-block:: python
245
246 >>> if rocket.position = event_horizon:
247 File "<stdin>", line 1
248 if rocket.position = event_horizon:
249 ^
250 SyntaxError: cannot assign to attribute here. Maybe you meant '==' instead of '='?
251
252* Usage of ``*`` in f-strings:
253
254.. code-block:: python
255
256 >>> f"Black holes {*all_black_holes} and revelations"
257 File "<stdin>", line 1
258 (*all_black_holes)
259 ^
260 SyntaxError: f-string: cannot use starred expression here
261
Pablo Galindo37494b42021-04-14 02:36:07 +0100262
263AttributeErrors
264~~~~~~~~~~~~~~~
265
266When printing :exc:`AttributeError`, :c:func:`PyErr_Display` will offer
Pablo Galindoc4073a22021-04-14 14:16:47 +0100267suggestions of similar attribute names in the object that the exception was
Pablo Galindo37494b42021-04-14 02:36:07 +0100268raised from:
269
270.. code-block:: python
271
272 >>> collections.namedtoplo
273 Traceback (most recent call last):
274 File "<stdin>", line 1, in <module>
275 AttributeError: module 'collections' has no attribute 'namedtoplo'. Did you mean: namedtuple?
276
277(Contributed by Pablo Galindo in :issue:`38530`.)
278
Pablo Galindo5bf8bf22021-04-14 15:10:33 +0100279NameErrors
280~~~~~~~~~~
281
282When printing :exc:`NameError` raised by the interpreter, :c:func:`PyErr_Display`
283will offer suggestions of simmilar variable names in the function that the exception
284was raised from:
285
286.. code-block:: python
287
288 >>> schwarzschild_black_hole = None
289 >>> schwarschild_black_hole
290 Traceback (most recent call last):
291 File "<stdin>", line 1, in <module>
292 NameError: name 'schwarschild_black_hole' is not defined. Did you mean: schwarzschild_black_hole?
293
294(Contributed by Pablo Galindo in :issue:`38530`.)
295
Mark Shannon6086ae72021-03-16 13:43:58 +0000296PEP 626: Precise line numbers for debugging and other tools
297-----------------------------------------------------------
298
299PEP 626 brings more precise and reliable line numbers for debugging, profiling and coverage tools.
300Tracing events, with the correct line number, are generated for all lines of code executed and only for lines of code that are executed.
301
Antti Haapalac3a478b2021-04-11 03:20:41 +0300302The ``f_lineno`` attribute of frame objects will always contain the expected line number.
Mark Shannon6086ae72021-03-16 13:43:58 +0000303
Mark Shannon148bc052021-03-19 17:30:24 +0000304The ``co_lnotab`` attribute of code objects is deprecated and will be removed in 3.12.
305Code that needs to convert from offset to line number should use the new ``co_lines()`` method instead.
Ken Jin11276cd2021-01-02 08:45:50 +0800306
Carol Willing41934b32021-02-28 15:43:17 -0800307PEP 634: Structural Pattern Matching
308------------------------------------
309
310Structural pattern matching has been added in the form of a *match statement*
311and *case statements* of patterns with associated actions. Patterns
312consist of sequences, mappings, primitive data types as well as class instances.
313Pattern matching enables programs to extract information from complex data types,
314branch on the structure of data, and apply specific actions based on different
315forms of data.
316
317Syntax and operations
318~~~~~~~~~~~~~~~~~~~~~
319
320The generic syntax of pattern matching is::
321
322 match subject:
323 case <pattern_1>:
324 <action_1>
325 case <pattern_2>:
326 <action_2>
327 case <pattern_3>:
328 <action_3>
329 case _:
330 <action_wildcard>
331
332A match statement takes an expression and compares its value to successive
333patterns given as one or more case blocks. Specifically, pattern matching
334operates by:
335
336 1. using data with type and shape (the ``subject``)
337 2. evaluating the ``subject`` in the ``match`` statement
338 3. comparing the subject with each pattern in a ``case`` statement
339 from top to bottom until a match is confirmed.
340 4. executing the action associated with the pattern of the confirmed
341 match
342 5. If an exact match is not confirmed, the last case, a wildcard ``_``,
343 if provided, will be used as the matching case. If an exact match is
blopblopy56816bb2021-03-25 18:14:22 +0200344 not confirmed and a wildcard case does not exist, the entire match
Carol Willing41934b32021-02-28 15:43:17 -0800345 block is a no-op.
346
347Declarative approach
348~~~~~~~~~~~~~~~~~~~~
349
350Readers may be aware of pattern matching through the simple example of matching
351a subject (data object) to a literal (pattern) with the switch statement found
352in C, Java or JavaScript (and many other languages). Often the switch statement
353is used for comparison of an object/expression with case statements containing
354literals.
355
356More powerful examples of pattern matching can be found in languages, such as
357Scala and Elixir. With structural pattern matching, the approach is "declarative" and
358explicitly states the conditions (the patterns) for data to match.
359
360While an "imperative" series of instructions using nested "if" statements
361could be used to accomplish something similar to structural pattern matching,
362it is less clear than the "declarative" approach. Instead the "declarative"
363approach states the conditions to meet for a match and is more readable through
364its explicit patterns. While structural pattern matching can be used in its
365simplest form comparing a variable to a literal in a case statement, its
366true value for Python lies in its handling of the subject's type and shape.
367
368Simple pattern: match to a literal
369~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
370
371Let's look at this example as pattern matching in its simplest form: a value,
372the subject, being matched to several literals, the patterns. In the example
373below, ``status`` is the subject of the match statement. The patterns are
374each of the case statements, where literals represent request status codes.
375The associated action to the case is executed after a match::
376
377 def http_error(status):
378 match status:
379 case 400:
380 return "Bad request"
381 case 404:
382 return "Not found"
383 case 418:
384 return "I'm a teapot"
385 case _:
386 return "Something's wrong with the Internet"
387
388If the above function is passed a ``status`` of 418, "I'm a teapot" is returned.
389If the above function is passed a ``status`` of 500, the case statement with
390``_`` will match as a wildcard, and "Something's wrong with the Internet" is
391returned.
392Note the last block: the variable name, ``_``, acts as a *wildcard* and insures
393the subject will always match. The use of ``_`` is optional.
394
395You can combine several literals in a single pattern using ``|`` ("or")::
396
397 case 401 | 403 | 404:
398 return "Not allowed"
399
400Behavior without the wildcard
401^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
402
403If we modify the above example by removing the last case block, the example
404becomes::
405
406 def http_error(status):
407 match status:
408 case 400:
409 return "Bad request"
410 case 404:
411 return "Not found"
412 case 418:
413 return "I'm a teapot"
414
415Without the use of ``_`` in a case statement, a match may not exist. If no
416match exists, the behavior is a no-op. For example, if ``status`` of 500 is
417passed, a no-op occurs.
418
Julien Palardb04f1cb2021-03-03 11:32:12 +0100419Patterns with a literal and variable
420~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Carol Willing41934b32021-02-28 15:43:17 -0800421
422Patterns can look like unpacking assignments, and a pattern may be used to bind
423variables. In this example, a data point can be unpacked to its x-coordinate
424and y-coordinate::
425
426 # point is an (x, y) tuple
427 match point:
428 case (0, 0):
429 print("Origin")
430 case (0, y):
431 print(f"Y={y}")
432 case (x, 0):
433 print(f"X={x}")
434 case (x, y):
435 print(f"X={x}, Y={y}")
436 case _:
437 raise ValueError("Not a point")
438
439The first pattern has two literals, ``(0, 0)``, and may be thought of as an
440extension of the literal pattern shown above. The next two patterns combine a
441literal and a variable, and the variable *binds* a value from the subject
442(``point``). The fourth pattern captures two values, which makes it
443conceptually similar to the unpacking assignment ``(x, y) = point``.
444
445Patterns and classes
446~~~~~~~~~~~~~~~~~~~~
447
448If you are using classes to structure your data, you can use as a pattern
449the class name followed by an argument list resembling a constructor. This
450pattern has the ability to capture class attributes into variables::
451
452 class Point:
453 x: int
454 y: int
455
456 def location(point):
457 match point:
458 case Point(x=0, y=0):
459 print("Origin is the point's location.")
460 case Point(x=0, y=y):
461 print(f"Y={y} and the point is on the y-axis.")
462 case Point(x=x, y=0):
463 print(f"X={x} and the point is on the x-axis.")
464 case Point():
465 print("The point is located somewhere else on the plane.")
466 case _:
467 print("Not a point")
468
469Patterns with positional parameters
470^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
471
472You can use positional parameters with some builtin classes that provide an
473ordering for their attributes (e.g. dataclasses). You can also define a specific
474position for attributes in patterns by setting the ``__match_args__`` special
475attribute in your classes. If it's set to ("x", "y"), the following patterns
476are all equivalent (and all bind the ``y`` attribute to the ``var`` variable)::
477
478 Point(1, var)
479 Point(1, y=var)
480 Point(x=1, y=var)
481 Point(y=var, x=1)
482
483Nested patterns
484~~~~~~~~~~~~~~~
485
486Patterns can be arbitrarily nested. For example, if our data is a short
487list of points, it could be matched like this::
488
489 match points:
490 case []:
491 print("No points in the list.")
492 case [Point(0, 0)]:
493 print("The origin is the only point in the list.")
494 case [Point(x, y)]:
495 print(f"A single point {x}, {y} is in the list.")
496 case [Point(0, y1), Point(0, y2)]:
497 print(f"Two points on the Y axis at {y1}, {y2} are in the list.")
498 case _:
499 print("Something else is found in the list.")
500
501Complex patterns and the wildcard
502~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
503
504To this point, the examples have used ``_`` alone in the last case statement.
505A wildcard can be used in more complex patterns, such as ``('error', code, _)``.
506For example::
507
508 match test_variable:
509 case ('warning', code, 40):
510 print("A warning has been received.")
511 case ('error', code, _):
Zackery Spytz0c4c4362021-04-14 10:16:11 -0600512 print(f"An error {code} occurred.")
Carol Willing41934b32021-02-28 15:43:17 -0800513
514In the above case, ``test_variable`` will match for ('error', code, 100) and
515('error', code, 800).
516
517Guard
518~~~~~
519
520We can add an ``if`` clause to a pattern, known as a "guard". If the
521guard is false, ``match`` goes on to try the next case block. Note
522that value capture happens before the guard is evaluated::
523
524 match point:
525 case Point(x, y) if x == y:
526 print(f"The point is located on the diagonal Y=X at {x}.")
527 case Point(x, y):
528 print(f"Point is not on the diagonal.")
529
530Other Key Features
531~~~~~~~~~~~~~~~~~~
532
533Several other key features:
534
535- Like unpacking assignments, tuple and list patterns have exactly the
536 same meaning and actually match arbitrary sequences. Technically,
537 the subject must be an instance of ``collections.abc.Sequence``.
538 Therefore, an important exception is that patterns don't match iterators.
539 Also, to prevent a common mistake, sequence patterns don't match strings.
540
541- Sequence patterns support wildcards: ``[x, y, *rest]`` and ``(x, y,
542 *rest)`` work similar to wildcards in unpacking assignments. The
543 name after ``*`` may also be ``_``, so ``(x, y, *_)`` matches a sequence
544 of at least two items without binding the remaining items.
545
546- Mapping patterns: ``{"bandwidth": b, "latency": l}`` captures the
547 ``"bandwidth"`` and ``"latency"`` values from a dict. Unlike sequence
548 patterns, extra keys are ignored. A wildcard ``**rest`` is also
Don Kirkby18701a02021-03-31 23:00:30 -0700549 supported. (But ``**_`` would be redundant, so is not allowed.)
Carol Willing41934b32021-02-28 15:43:17 -0800550
551- Subpatterns may be captured using the ``as`` keyword::
552
553 case (Point(x1, y1), Point(x2, y2) as p2): ...
554
555 This binds x1, y1, x2, y2 like you would expect without the ``as`` clause,
556 and p2 to the entire second item of the subject.
557
558- Most literals are compared by equality. However, the singletons ``True``,
559 ``False`` and ``None`` are compared by identity.
560
561- Named constants may be used in patterns. These named constants must be
562 dotted names to prevent the constant from being interpreted as a capture
563 variable::
564
565 from enum import Enum
566 class Color(Enum):
567 RED = 0
568 GREEN = 1
569 BLUE = 2
570
571 match color:
572 case Color.RED:
573 print("I see red!")
574 case Color.GREEN:
575 print("Grass is green")
576 case Color.BLUE:
577 print("I'm feeling the blues :(")
578
579For the full specification see :pep:`634`. Motivation and rationale
580are in :pep:`635`, and a longer tutorial is in :pep:`636`.
581
Pablo Galindo805ede82021-01-21 17:36:35 +0000582
Inada Naoki48274832021-03-29 12:28:14 +0900583.. _whatsnew310-pep597:
584
585Optional ``EncodingWarning`` and ``encoding="locale"`` option
586-------------------------------------------------------------
587
588The default encoding of :class:`TextIOWrapper` and :func:`open` is
589platform and locale dependent. Since UTF-8 is used on most Unix
590platforms, omitting ``encoding`` option when opening UTF-8 files
Don Kirkby18701a02021-03-31 23:00:30 -0700591(e.g. JSON, YAML, TOML, Markdown) is a very common bug. For example::
Inada Naoki48274832021-03-29 12:28:14 +0900592
593 # BUG: "rb" mode or encoding="utf-8" should be used.
594 with open("data.json") as f:
Don Kirkby18701a02021-03-31 23:00:30 -0700595 data = json.load(f)
Inada Naoki48274832021-03-29 12:28:14 +0900596
Don Kirkby18701a02021-03-31 23:00:30 -0700597To find this type of bug, optional ``EncodingWarning`` is added.
Inada Naoki48274832021-03-29 12:28:14 +0900598It is emitted when :data:`sys.flags.warn_default_encoding <sys.flags>`
599is true and locale-specific default encoding is used.
600
601``-X warn_default_encoding`` option and :envvar:`PYTHONWARNDEFAULTENCODING`
602are added to enable the warning.
603
604See :ref:`io-text-encoding` for more information.
605
606
Ken Jin727a68b2021-03-03 08:52:03 +0800607New Features Related to Type Annotations
608========================================
Pablo Galindo805ede82021-01-21 17:36:35 +0000609
Ken Jin727a68b2021-03-03 08:52:03 +0800610This section covers major changes affecting :pep:`484` type annotations and
611the :mod:`typing` module.
Pablo Galindo805ede82021-01-21 17:36:35 +0000612
613
Ken Jin727a68b2021-03-03 08:52:03 +0800614PEP 563: Postponed Evaluation of Annotations Becomes Default
615------------------------------------------------------------
Pablo Galindo805ede82021-01-21 17:36:35 +0000616
Ken Jin727a68b2021-03-03 08:52:03 +0800617In Python 3.7, postponed evaluation of annotations was added,
618to be enabled with a ``from __future__ import annotations``
619directive. In 3.10 this became the default behavior, even
620without that future directive. With this being default, all
621annotations stored in :attr:`__annotations__` will be strings.
622If needed, annotations can be resolved at runtime using
623:func:`typing.get_type_hints`. See :pep:`563` for a full
624description. Also, the :func:`inspect.signature` will try to
625resolve types from now on, and when it fails it will fall back to
626showing the string annotations. (Contributed by Batuhan Taskaya
627in :issue:`38605`.)
Pablo Galindo805ede82021-01-21 17:36:35 +0000628
Ken Jin727a68b2021-03-03 08:52:03 +0800629
630PEP 604: New Type Union Operator
631--------------------------------
632
633A new type union operator was introduced which enables the syntax ``X | Y``.
634This provides a cleaner way of expressing 'either type X or type Y' instead of
635using :data:`typing.Union`, especially in type hints (annotations).
636
637In previous versions of Python, to apply a type hint for functions accepting
638arguments of multiple types, :data:`typing.Union` was used::
639
640 def square(number: Union[int, float]) -> Union[int, float]:
641 return number ** 2
642
643
644Type hints can now be written in a more succinct manner::
645
646 def square(number: int | float) -> int | float:
647 return number ** 2
648
649
650This new syntax is also accepted as the second argument to :func:`isinstance`
651and :func:`issubclass`::
652
653 >>> isinstance(1, int | str)
654 True
655
656See :ref:`types-union` and :pep:`604` for more details.
657
658(Contributed by Maggie Moss and Philippe Prados in :issue:`41428`.)
659
660
661PEP 612: Parameter Specification Variables
662------------------------------------------
663
664Two new options to improve the information provided to static type checkers for
665:pep:`484`\ 's ``Callable`` have been added to the :mod:`typing` module.
666
667The first is the parameter specification variable. They are used to forward the
668parameter types of one callable to another callable -- a pattern commonly
669found in higher order functions and decorators. Examples of usage can be found
670in :class:`typing.ParamSpec`. Previously, there was no easy way to type annotate
671dependency of parameter types in such a precise manner.
672
673The second option is the new ``Concatenate`` operator. It's used in conjunction
674with parameter specification variables to type annotate a higher order callable
675which adds or removes parameters of another callable. Examples of usage can
676be found in :class:`typing.Concatenate`.
677
678See :class:`typing.Callable`, :class:`typing.ParamSpec`,
Jelle Zijlstra52243362021-04-10 19:57:05 -0700679:class:`typing.Concatenate`, :class:`typing.ParamSpecArgs`,
680:class:`typing.ParamSpecKwargs`, and :pep:`612` for more details.
Ken Jin727a68b2021-03-03 08:52:03 +0800681
Jelle Zijlstra52243362021-04-10 19:57:05 -0700682(Contributed by Ken Jin in :issue:`41559`, with minor enhancements by Jelle
683Zijlstra in :issue:`43783`. PEP written by Mark Mendoza.)
Ken Jin727a68b2021-03-03 08:52:03 +0800684
685
686PEP 613: TypeAlias Annotation
687-----------------------------
688
689:pep:`484` introduced the concept of type aliases, only requiring them to be
690top-level unannotated assignments. This simplicity sometimes made it difficult
691for type checkers to distinguish between type aliases and ordinary assignments,
692especially when forward references or invalid types were involved. Compare::
693
694 StrCache = 'Cache[str]' # a type alias
695 LOG_PREFIX = 'LOG[DEBUG]' # a module constant
696
697Now the :mod:`typing` module has a special annotation :data:`TypeAlias` to
698declare type aliases more explicitly::
699
700 StrCache: TypeAlias = 'Cache[str]' # a type alias
701 LOG_PREFIX = 'LOG[DEBUG]' # a module constant
702
703See :pep:`613` for more details.
704
705(Contributed by Mikhail Golubev in :issue:`41923`.)
706
Pablo Galindo805ede82021-01-21 17:36:35 +0000707
Pablo Galindod4fe0982020-05-19 03:33:01 +0100708Other Language Changes
709======================
710
Ken Jin727a68b2021-03-03 08:52:03 +0800711* The :class:`int` type has a new method :meth:`int.bit_count`, returning the
712 number of ones in the binary expansion of a given integer, also known
713 as the population count. (Contributed by Niklas Fiekas in :issue:`29882`.)
714
715* The views returned by :meth:`dict.keys`, :meth:`dict.values` and
716 :meth:`dict.items` now all have a ``mapping`` attribute that gives a
717 :class:`types.MappingProxyType` object wrapping the original
718 dictionary. (Contributed by Dennis Sweeney in :issue:`40890`.)
719
720* :pep:`618`: The :func:`zip` function now has an optional ``strict`` flag, used
721 to require that all the iterables have an equal length.
722
Serhiy Storchaka578c3952020-05-26 18:43:38 +0300723* Builtin and extension functions that take integer arguments no longer accept
724 :class:`~decimal.Decimal`\ s, :class:`~fractions.Fraction`\ s and other
725 objects that can be converted to integers only with a loss (e.g. that have
726 the :meth:`~object.__int__` method but do not have the
727 :meth:`~object.__index__` method).
728 (Contributed by Serhiy Storchaka in :issue:`37999`.)
Ken Jin727a68b2021-03-03 08:52:03 +0800729
Alexcc02b4f2021-02-26 21:58:39 +0200730* If :func:`object.__ipow__` returns :const:`NotImplemented`, the operator will
731 correctly fall back to :func:`object.__pow__` and :func:`object.__rpow__` as expected.
732 (Contributed by Alex Shkop in :issue:`38302`.)
Pablo Galindod4fe0982020-05-19 03:33:01 +0100733
Lysandros Nikolaoua85fefe2020-11-19 01:49:28 +0200734* Assignment expressions can now be used unparenthesized within set literals
735 and set comprehensions, as well as in sequence indexes (but not slices).
736
Victor Stinnera3c3ffa2021-02-18 12:35:37 +0100737* Functions have a new ``__builtins__`` attribute which is used to look for
738 builtin symbols when a function is executed, instead of looking into
Victor Stinner46496f92021-02-20 15:17:18 +0100739 ``__globals__['__builtins__']``. The attribute is initialized from
740 ``__globals__["__builtins__"]`` if it exists, else from the current builtins.
Victor Stinnera3c3ffa2021-02-18 12:35:37 +0100741 (Contributed by Mark Shannon in :issue:`42990`.)
742
Joshua Bronsonf0a6fde2021-03-23 18:47:21 -0400743* Two new builtin functions -- :func:`aiter` and :func:`anext` have been added
744 to provide asynchronous counterparts to :func:`iter` and :func:`next`,
745 respectively.
746 (Contributed by Joshua Bronson, Daniel Pope, and Justin Wang in :issue:`31861`.)
747
Victor Stinner507a5742021-04-09 17:51:22 +0200748* Static methods (:func:`@staticmethod <staticmethod>`) and class methods
749 (:func:`@classmethod <classmethod>`) now inherit the method attributes
750 (``__module__``, ``__name__``, ``__qualname__``, ``__doc__``,
751 ``__annotations__``) and have a new ``__wrapped__`` attribute.
Victor Stinner553ee272021-04-12 00:21:22 +0200752 Moreover, static methods are now callable as regular functions.
Victor Stinner507a5742021-04-09 17:51:22 +0200753 (Contributed by Victor Stinner in :issue:`43682`.)
754
Pablo Galindod4fe0982020-05-19 03:33:01 +0100755
756New Modules
757===========
758
759* None yet.
760
761
762Improved Modules
763================
764
Tomáš Hrnčiarfb35fa42021-01-12 01:41:35 +0100765argparse
766--------
767
768Misleading phrase "optional arguments" was replaced with "options" in argparse help. Some tests might require adaptation if they rely on exact output match.
769(Contributed by Raymond Hettinger in :issue:`9694`.)
770
Zackery Spytzafd12652021-04-02 09:28:35 -0600771array
772-----
773
774The :meth:`~array.array.index` method of :class:`array.array` now has
775optional *start* and *stop* parameters.
776(Contributed by Anders Lorentsen and Zackery Spytz in :issue:`31956`.)
777
Filipe Laíns4ce6faa2020-08-10 15:48:20 +0100778base64
779------
780
781Add :func:`base64.b32hexencode` and :func:`base64.b32hexdecode` to support the
782Base32 Encoding with Extended Hex Alphabet.
783
Hai Shid332e7b2020-09-29 05:41:11 +0800784codecs
785------
786
787Add a :func:`codecs.unregister` function to unregister a codec search function.
788(Contributed by Hai Shi in :issue:`41842`.)
789
kjd75f6f72020-12-19 01:39:26 +0800790collections.abc
791---------------
792
793The ``__args__`` of the :ref:`parameterized generic <types-genericalias>` for
794:class:`collections.abc.Callable` are now consistent with :data:`typing.Callable`.
795:class:`collections.abc.Callable` generic now flattens type parameters, similar
796to what :data:`typing.Callable` currently does. This means that
797``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
798``(int, str, str)``; previously this was ``([int, str], str)``. To allow this
799change, :class:`types.GenericAlias` can now be subclassed, and a subclass will
800be returned when subscripting the :class:`collections.abc.Callable` type. Note
801that a :exc:`TypeError` may be raised for invalid forms of parameterizing
802:class:`collections.abc.Callable` which may have passed silently in Python 3.9.
803(Contributed by Ken Jin in :issue:`42195`.)
804
Joongi Kim3eb28462020-11-11 00:19:11 +0900805contextlib
806----------
807
808Add a :func:`contextlib.aclosing` context manager to safely close async generators
809and objects representing asynchronously released resources.
810(Contributed by Joongi Kim and John Belmonte in :issue:`41229`.)
811
Tom Gringauz9c98e8c2020-11-18 00:58:35 +0200812Add asynchronous context manager support to :func:`contextlib.nullcontext`.
813(Contributed by Tom Gringauz in :issue:`41543`.)
814
Hans Petter Janssonda4e09f2020-08-03 22:51:33 -0500815curses
816------
817
818The extended color functions added in ncurses 6.1 will be used transparently
819by :func:`curses.color_content`, :func:`curses.init_color`,
820:func:`curses.init_pair`, and :func:`curses.pair_content`. A new function,
821:func:`curses.has_extended_color_support`, indicates whether extended color
822support is provided by the underlying ncurses library.
823(Contributed by Jeffrey Kintscher and Hans Petter Jansson in :issue:`36982`.)
824
Zackery Spytz14cfa322021-01-14 02:40:09 -0700825The ``BUTTON5_*`` constants are now exposed in the :mod:`curses` module if
826they are provided by the underlying curses library.
827(Contributed by Zackery Spytz in :issue:`39273`.)
828
Steve Dower62949f62021-01-29 21:48:55 +0000829.. _distutils-deprecated:
830
Victor Stinner0e2a0f72021-01-09 00:35:01 +0100831distutils
832---------
833
Steve Dower62949f62021-01-29 21:48:55 +0000834The entire ``distutils`` package is deprecated, to be removed in Python
8353.12. Its functionality for specifying package builds has already been
836completely replaced by third-party packages ``setuptools`` and
837``packaging``, and most other commonly used APIs are available elsewhere
838in the standard library (such as :mod:`platform`, :mod:`shutil`,
839:mod:`subprocess` or :mod:`sysconfig`). There are no plans to migrate
840any other functionality from ``distutils``, and applications that are
841using other functions should plan to make private copies of the code.
842Refer to :pep:`632` for discussion.
843
Victor Stinner0e2a0f72021-01-09 00:35:01 +0100844The ``bdist_wininst`` command deprecated in Python 3.8 has been removed.
ravcio6cd5b012021-01-21 11:23:46 +0100845The ``bdist_wheel`` command is now recommended to distribute binary packages
Victor Stinner0e2a0f72021-01-09 00:35:01 +0100846on Windows.
847(Contributed by Victor Stinner in :issue:`42802`.)
848
Brett Cannon825ac382020-11-06 18:45:56 -0800849doctest
850-------
851
852When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
853(Contributed by Brett Cannon in :issue:`42133`.)
854
Hai Shic5b049b2020-10-14 23:43:31 +0800855encodings
856---------
Pablo Galindob4f90892021-03-10 00:53:57 +0000857
Hai Shic5b049b2020-10-14 23:43:31 +0800858:func:`encodings.normalize_encoding` now ignores non-ASCII characters.
859(Contributed by Hai Shi in :issue:`39337`.)
860
Ethan Furmanb7751062021-03-30 21:17:26 -0700861enum
862----
863
864:class:`Enum` :func:`__repr__` now returns ``enum_name.member_name`` and
865:func:`__str__` now returns ``member_name``. Stdlib enums available as
866module constants have a :func:`repr` of ``module_name.member_name``.
867(Contributed by Ethan Furman in :issue:`40066`.)
868
Inada Naoki333d10c2021-04-14 14:12:58 +0900869fileinput
870---------
871
872Added *encoding* and *errors* parameters in :func:`fileinput.input` and
873:class:`fileinput.FileInput`.
874(Contributed by Inada Naoki in :issue:`43712`.)
875
876:func:`fileinput.hook_compressed` now returns :class:`TextIOWrapper` object
877when *mode* is "r" and file is compressed, like uncompressed files.
878(Contributed by Inada Naoki in :issue:`5758`.)
879
Pablo Galindob4f90892021-03-10 00:53:57 +0000880gc
881--
882
883Added audit hooks for :func:`gc.get_objects`, :func:`gc.get_referrers` and
884:func:`gc.get_referents`. (Contributed by Pablo Galindo in :issue:`43439`.)
885
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +0300886glob
887----
888
889Added the *root_dir* and *dir_fd* parameters in :func:`~glob.glob` and
890:func:`~glob.iglob` which allow to specify the root directory for searching.
891(Contributed by Serhiy Storchaka in :issue:`38144`.)
892
Jason R. Coombs35d50682021-03-14 22:20:49 -0400893importlib.metadata
894------------------
895
896Feature parity with ``importlib_metadata`` 3.7.
897
898:func:`importlib.metadata.entry_points` now provides a nicer experience
899for selecting entry points by group and name through a new
900:class:`importlib.metadata.EntryPoints` class.
901
902Added :func:`importlib.metadata.packages_distributions` for resolving
903top-level Python modules and packages to their
904:class:`importlib.metadata.Distribution`.
905
Brett Cannon825ac382020-11-06 18:45:56 -0800906inspect
907-------
908
909When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
910(Contributed by Brett Cannon in :issue:`42133`.)
911
Batuhan Taskayaeee1c772020-12-24 01:45:13 +0300912Added *globalns* and *localns* parameters in :func:`~inspect.signature` and
913:meth:`inspect.Signature.from_callable` to retrieve the annotations in given
914local and global namespaces.
915(Contributed by Batuhan Taskaya in :issue:`41960`.)
916
Brett Cannon825ac382020-11-06 18:45:56 -0800917linecache
918---------
919
920When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
921(Contributed by Brett Cannon in :issue:`42133`.)
922
pxinwr3405e052020-08-07 13:21:52 +0800923os
924--
925
926Added :func:`os.cpu_count()` support for VxWorks RTOS.
927(Contributed by Peixing Xin in :issue:`41440`.)
928
Christian Heimescd9fed62020-11-13 19:48:52 +0100929Added a new function :func:`os.eventfd` and related helpers to wrap the
930``eventfd2`` syscall on Linux.
931(Contributed by Christian Heimes in :issue:`41001`.)
932
Pablo Galindoa57b3d32020-11-17 00:00:38 +0000933Added :func:`os.splice()` that allows to move data between two file
934descriptors without copying between kernel address space and user
935address space, where one of the file descriptors must refer to a
936pipe. (Contributed by Pablo Galindo in :issue:`41625`.)
937
Dong-hee Naf917c242021-02-04 08:32:55 +0900938Added :data:`~os.O_EVTONLY`, :data:`~os.O_FSYNC`, :data:`~os.O_SYMLINK`
939and :data:`~os.O_NOFOLLOW_ANY` for macOS.
940(Contributed by Dong-hee Na in :issue:`43106`.)
941
Joshua Cannon45205842020-11-20 09:40:39 -0600942pathlib
943-------
944
Yaroslav Pankovych79d2e622020-11-23 22:06:22 +0200945Added slice support to :attr:`PurePath.parents <pathlib.PurePath.parents>`.
Joshua Cannon45205842020-11-20 09:40:39 -0600946(Contributed by Joshua Cannon in :issue:`35498`)
947
Yaroslav Pankovych79d2e622020-11-23 22:06:22 +0200948Added negative indexing support to :attr:`PurePath.parents
949<pathlib.PurePath.parents>`.
950(Contributed by Yaroslav Pankovych in :issue:`21041`)
951
Christian Heimes5c73afc2020-11-30 22:34:45 +0100952platform
953--------
954
955Added :func:`platform.freedesktop_os_release()` to retrieve operation system
956identification from `freedesktop.org os-release
957<https://www.freedesktop.org/software/systemd/man/os-release.html>`_ standard file.
958(Contributed by Christian Heimes in :issue:`28468`)
959
Lewis Gaul11159d22021-04-14 00:59:24 +0100960pprint
961------
962
963:mod:`pprint` can now pretty-print :class:`dataclasses.dataclass` instances.
964(Contributed by Lewis Gaul in :issue:`43080`.)
965
Gregory Schevchenkodaff3902020-07-25 22:58:45 +0300966py_compile
967----------
968
969Added ``--quiet`` option to command-line interface of :mod:`py_compile`.
970(Contributed by Gregory Schevchenko in :issue:`38731`.)
971
Aviral Srivastava000cde52021-02-01 09:38:44 -0800972pyclbr
973------
974
975Added an ``end_lineno`` attribute to the ``Function`` and ``Class``
976objects in the tree returned by :func:`pyclbr.readline` and
977:func:`pyclbr.readline_ex`. It matches the existing (start) ``lineno``.
978(Contributed by Aviral Srivastava in :issue:`38307`.)
979
Zackery Spytzdf592732020-10-29 03:44:35 -0600980shelve
981------
982
983The :mod:`shelve` module now uses :data:`pickle.DEFAULT_PROTOCOL` by default
984instead of :mod:`pickle` protocol ``3`` when creating shelves.
985(Contributed by Zackery Spytz in :issue:`34204`.)
986
Brett Cannon825ac382020-11-06 18:45:56 -0800987site
988----
989
990When a module does not define ``__loader__``, fall back to ``__spec__.loader``.
991(Contributed by Brett Cannon in :issue:`42133`.)
992
Christian Heimes03c8ddd2020-11-20 09:26:07 +0100993socket
994------
995
996The exception :exc:`socket.timeout` is now an alias of :exc:`TimeoutError`.
997(Contributed by Christian Heimes in :issue:`42413`.)
998
Rui Cunhab05b48d2021-03-20 22:04:56 +0000999Added option to create MPTCP sockets with ``IPPROTO_MPTCP``
1000(Contributed by Rui Cunha in :issue:`43571`.)
1001
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001002sys
1003---
1004
1005Add :data:`sys.orig_argv` attribute: the list of the original command line
1006arguments passed to the Python executable.
1007(Contributed by Victor Stinner in :issue:`23427`.)
1008
Victor Stinner9852cb32021-01-25 23:12:50 +01001009Add :data:`sys.stdlib_module_names`, containing the list of the standard library
Victor Stinnerdb584bd2021-01-25 13:24:42 +01001010module names.
1011(Contributed by Victor Stinner in :issue:`42955`.)
1012
Antoine Pitrouba251c22021-03-11 23:35:45 +01001013_thread
1014-------
1015
1016:func:`_thread.interrupt_main` now takes an optional signal number to
1017simulate (the default is still :data:`signal.SIGINT`).
1018(Contributed by Antoine Pitrou in :issue:`43356`.)
1019
Mario Corchero0001a1b2020-11-04 10:27:43 +01001020threading
1021---------
1022
1023Added :func:`threading.gettrace` and :func:`threading.getprofile` to
1024retrieve the functions set by :func:`threading.settrace` and
1025:func:`threading.setprofile` respectively.
1026(Contributed by Mario Corchero in :issue:`42251`.)
1027
Mario Corchero750c5ab2020-11-12 18:27:44 +01001028Add :data:`threading.__excepthook__` to allow retrieving the original value
1029of :func:`threading.excepthook` in case it is set to a broken or a different
1030value.
1031(Contributed by Mario Corchero in :issue:`42308`.)
1032
Zackery Spytz91e93792020-11-05 15:18:44 -07001033traceback
1034---------
1035
1036The :func:`~traceback.format_exception`,
1037:func:`~traceback.format_exception_only`, and
1038:func:`~traceback.print_exception` functions can now take an exception object
1039as a positional-only argument.
1040(Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.)
1041
Bas van Beek0d0e9fe2020-09-22 17:55:34 +02001042types
1043-----
1044
1045Reintroduced the :data:`types.EllipsisType`, :data:`types.NoneType`
1046and :data:`types.NotImplementedType` classes, providing a new set
1047of types readily interpretable by type checkers.
1048(Contributed by Bas van Beek in :issue:`41810`.)
1049
kj46873382020-11-19 11:44:24 +07001050typing
1051------
1052
Ken Jin727a68b2021-03-03 08:52:03 +08001053For major changes, see `New Features Related to Type Annotations`_.
1054
kj46873382020-11-19 11:44:24 +07001055The behavior of :class:`typing.Literal` was changed to conform with :pep:`586`
1056and to match the behavior of static type checkers specified in the PEP.
1057
10581. ``Literal`` now de-duplicates parameters.
10592. Equality comparisons between ``Literal`` objects are now order independent.
10603. ``Literal`` comparisons now respects types. For example,
1061 ``Literal[0] == Literal[False]`` previously evaluated to ``True``. It is
1062 now ``False``. To support this change, the internally used type cache now
1063 supports differentiating types.
10644. ``Literal`` objects will now raise a :exc:`TypeError` exception during
1065 equality comparisons if one of their parameters are not :term:`immutable`.
1066 Note that declaring ``Literal`` with mutable parameters will not throw
1067 an error::
1068
1069 >>> from typing import Literal
1070 >>> Literal[{0}]
1071 >>> Literal[{0}] == Literal[{False}]
1072 Traceback (most recent call last):
1073 File "<stdin>", line 1, in <module>
1074 TypeError: unhashable type: 'set'
1075
1076(Contributed by Yurii Karabas in :issue:`42345`.)
1077
Mark Dickinsonc8c70e72020-09-19 21:38:11 +01001078unittest
1079--------
1080
1081Add new method :meth:`~unittest.TestCase.assertNoLogs` to complement the
1082existing :meth:`~unittest.TestCase.assertLogs`. (Contributed by Kit Yan Choi
1083in :issue:`39385`.)
1084
Adam Goldschmidtfcbe0cb2021-02-15 00:41:57 +02001085urllib.parse
1086------------
1087
1088Python versions earlier than Python 3.10 allowed using both ``;`` and ``&`` as
1089query parameter separators in :func:`urllib.parse.parse_qs` and
1090:func:`urllib.parse.parse_qsl`. Due to security concerns, and to conform with
1091newer W3C recommendations, this has been changed to allow only a single
1092separator key, with ``&`` as the default. This change also affects
1093:func:`cgi.parse` and :func:`cgi.parse_multipart` as they use the affected
1094functions internally. For more details, please see their respective
1095documentation.
1096(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin in :issue:`42967`.)
1097
Zackery Spytze28b8c92020-08-09 04:50:53 -06001098xml
1099---
1100
1101Add a :class:`~xml.sax.handler.LexicalHandler` class to the
1102:mod:`xml.sax.handler` module.
1103(Contributed by Jonathan Gossage and Zackery Spytz in :issue:`35018`.)
1104
Brett Cannond2e94bb2020-11-13 15:14:58 -08001105zipimport
1106---------
1107Add methods related to :pep:`451`: :meth:`~zipimport.zipimporter.find_spec`,
1108:meth:`zipimport.zipimporter.create_module`, and
1109:meth:`zipimport.zipimporter.exec_module`.
1110(Contributed by Brett Cannon in :issue:`42131`.
1111
Serhiy Storchaka8a64cea2020-06-18 22:08:27 +03001112
Pablo Galindod4fe0982020-05-19 03:33:01 +01001113Optimizations
1114=============
1115
Serhiy Storchaka12f43342020-07-20 15:53:55 +03001116* Constructors :func:`str`, :func:`bytes` and :func:`bytearray` are now faster
1117 (around 30--40% for small objects).
1118 (Contributed by Serhiy Storchaka in :issue:`41334`.)
1119
Victor Stinner2c2a4f32020-06-18 01:20:51 +02001120* The :mod:`runpy` module now imports fewer modules.
Victor Stinnercd27af72021-03-23 20:22:40 +01001121 The ``python3 -m module-name`` command startup time is 1.4x faster in
1122 average. On Linux, ``python3 -I -m module-name`` imports 69 modules on Python
1123 3.9, whereas it only imports 51 modules (-18) on Python 3.10.
1124 (Contributed by Victor Stinner in :issue:`41006` and :issue:`41718`.)
Victor Stinner4c18fc82020-06-17 23:58:58 +02001125
Pablo Galindo9e8fe192021-01-03 04:37:46 +00001126* The ``LOAD_ATTR`` instruction now uses new "per opcode cache" mechanism. It
Pablo Galindoa776da92021-01-31 22:55:48 +00001127 is about 36% faster now for regular attributes and 44% faster for slots.
1128 (Contributed by Pablo Galindo and Yury Selivanov in :issue:`42093` and Guido
1129 van Rossum in :issue:`42927`, based on ideas implemented originally in PyPy
1130 and MicroPython.)
Pablo Galindod4fe0982020-05-19 03:33:01 +01001131
Victor Stinner85918e42021-04-12 23:27:35 +02001132* When building Python with :option:`--enable-optimizations` now
Pablo Galindob451b0e2020-10-21 22:46:52 +01001133 ``-fno-semantic-interposition`` is added to both the compile and link line.
Victor Stinner85918e42021-04-12 23:27:35 +02001134 This speeds builds of the Python interpreter created with :option:`--enable-shared`
Pablo Galindob451b0e2020-10-21 22:46:52 +01001135 with ``gcc`` by up to 30%. See `this article
1136 <https://developers.redhat.com/blog/2020/06/25/red-hat-enterprise-linux-8-2-brings-faster-python-3-8-run-speeds/>`_
1137 for more details. (Contributed by Victor Stinner and Pablo Galindo in
Brett Cannon2de50972020-12-04 15:39:21 -08001138 :issue:`38980`.)
1139
Yurii Karabas73019792020-11-25 12:43:18 +02001140* Function parameters and their annotations are no longer computed at runtime,
1141 but rather at compilation time. They are stored as a tuple of strings at the
Pablo Galindo8747c1f2021-03-04 01:29:29 +00001142 bytecode level. It is now around 2 times faster to create a function with
1143 parameter annotations. (Contributed by Yurii Karabas and Inada Naoki
1144 in :issue:`42202`)
Yurii Karabas73019792020-11-25 12:43:18 +02001145
Dennis Sweeneye8f5ddd2021-02-28 16:32:04 -05001146* Substring search functions such as ``str1 in str2`` and ``str2.find(str1)``
1147 now sometimes use Crochemore & Perrin's "Two-Way" string searching
1148 algorithm to avoid quadratic behavior on long strings. (Contributed
1149 by Dennis Sweeney in :issue:`41972`)
1150
Pablo Galindoa054f6b2021-03-24 00:04:52 +00001151* Added micro-optimizations to ``_PyType_Lookup()`` to improve type attribute cache lookup
1152 performance in the common case of cache hits. This makes the interpreter 1.04 times faster
1153 in average (Contributed by Dino Viehland in :issue:`43452`)
1154
Dong-hee Naefccff92021-04-07 00:43:59 +09001155* Following built-in functions now support the faster :pep:`590` vectorcall calling convention:
1156 :func:`map`, :func:`filter`, :func:`reversed`, :func:`bool` and :func:`float`.
1157 (Contributed by Dong-hee Na and Jeroen Demeyerin in :issue:`43575`, :issue:`43287`, :issue:`41922`, :issue:`41873` and :issue:`41870`)
1158
Inada Naoki695d47b2021-04-14 08:22:49 +09001159* :class:`BZ2File` performance is improved by removing internal ``RLock``.
1160 This makes :class:`BZ2File` thread unsafe in the face of multiple simultaneous
1161 readers or writers, just like its equivalent classes in :mod:`gzip` and
1162 :mod:`lzma` have always been. (Contributed by Inada Naoki in :issue:`43785`).
1163
Pablo Galindod4fe0982020-05-19 03:33:01 +01001164Deprecated
1165==========
1166
Brett Cannon04523c52020-10-23 18:10:54 -07001167* Starting in this release, there will be a concerted effort to begin
1168 cleaning up old import semantics that were kept for Python 2.7
1169 compatibility. Specifically,
1170 :meth:`~importlib.abc.PathEntryFinder.find_loader`/:meth:`~importlib.abc.Finder.find_module`
1171 (superseded by :meth:`~importlib.abc.Finder.find_spec`),
1172 :meth:`~importlib.abc.Loader.load_module`
1173 (superseded by :meth:`~importlib.abc.Loader.exec_module`),
1174 :meth:`~importlib.abc.Loader.module_repr` (which the import system
1175 takes care of for you), the ``__package__`` attribute
1176 (superseded by ``__spec__.parent``), the ``__loader__`` attribute
1177 (superseded by ``__spec__.loader``), and the ``__cached__`` attribute
1178 (superseded by ``__spec__.cached``) will slowly be removed (as well
1179 as other classes and methods in :mod:`importlib`).
1180 :exc:`ImportWarning` and/or :exc:`DeprecationWarning` will be raised
1181 as appropriate to help identify code which needs updating during
1182 this transition.
1183
Steve Dower62949f62021-01-29 21:48:55 +00001184* The entire ``distutils`` namespace is deprecated, to be removed in
1185 Python 3.12. Refer to the :ref:`module changes <distutils-deprecated>`
1186 section for more information.
1187
Serhiy Storchakaf066bd92021-01-25 23:02:04 +02001188* Non-integer arguments to :func:`random.randrange` are deprecated.
1189 The :exc:`ValueError` is deprecated in favor of a :exc:`TypeError`.
1190 (Contributed by Serhiy Storchaka and Raymond Hettinger in :issue:`37319`.)
1191
Brett Cannon2de50972020-12-04 15:39:21 -08001192* The various ``load_module()`` methods of :mod:`importlib` have been
1193 documented as deprecated since Python 3.6, but will now also trigger
1194 a :exc:`DeprecationWarning`. Use
1195 :meth:`~importlib.abc.Loader.exec_module` instead.
1196 (Contributed by Brett Cannon in :issue:`26131`.)
1197
1198* :meth:`zimport.zipimporter.load_module` has been deprecated in
1199 preference for :meth:`~zipimport.zipimporter.exec_module`.
1200 (Contributed by Brett Cannon in :issue:`26131`.)
1201
1202* The use of :meth:`~importlib.abc.Loader.load_module` by the import
1203 system now triggers an :exc:`ImportWarning` as
1204 :meth:`~importlib.abc.Loader.exec_module` is preferred.
1205 (Contributed by Brett Cannon in :issue:`26131`.)
1206
Brett Cannona7ff6df2021-03-30 08:43:03 -07001207* The use of :meth:`importlib.abc.MetaPathFinder.find_module` and
1208 :meth:`importlib.abc.PathEntryFinder.find_module` by the import system now
1209 trigger an :exc:`ImportWarning` as
1210 :meth:`importlib.abc.MetaPathFinder.find_spec` and
1211 :meth:`importlib.abc.PathEntryFinder.find_spec`
1212 are preferred, respectively. You can use
1213 :func:`importlib.util.spec_from_loader` to help in porting.
Brett Cannonf97dc802021-04-02 12:35:32 -07001214 (Contributed by Brett Cannon in :issue:`42134`.)
1215
1216* The use of :meth:`importlib.abc.PathEntryFinder.find_loader` by the import
1217 system now triggers an :exc:`ImportWarning` as
1218 :meth:`importlib.abc.PathEntryFinder.find_spec` is preferred. You can use
1219 :func:`importlib.util.spec_from_loader` to help in porting.
1220 (Contributed by Brett Cannon in :issue:`43672`.)
Brett Cannona7ff6df2021-03-30 08:43:03 -07001221
Brett Cannon57c6cb52021-04-06 08:56:57 -07001222* The various implementations of
1223 :meth:`importlib.abc.MetaPathFinder.find_module` (
1224 :meth:`importlib.machinery.BuiltinImporter.find_module`,
1225 :meth:`importlib.machinery.FrozenImporter.find_module`,
1226 :meth:`importlib.machinery.WindowsRegistryFinder.find_module`,
1227 :meth:`importlib.machinery.PathFinder.find_module`,
1228 :meth:`importlib.abc.MetaPathFinder.find_module`),
1229 :meth:`importlib.abc.PathEntryFinder.find_module` (
1230 :meth:`importlib.machinery.FileFinder.find_module`,
1231 ), and
1232 :meth:`importlib.abc.PathEntryFinder.find_loader` (
1233 :meth:`importlib.machinery.FileFinder.find_loader`
1234 ) now raise :exc:`DeprecationWarning` and are slated for removal in
1235 Python 3.12 (previously they were documented as deprecated in Python 3.4).
1236 (Contributed by Brett Cannon in :issue:`42135`.)
1237
1238* :class:`importlib.abc.Finder` is deprecated (including its sole method,
1239 :meth:`~importlib.abc.Finder.find_module`). Both
1240 :class:`importlib.abc.MetaPathFinder` and :class:`importlib.abc.PathEntryFinder`
1241 no longer inherit from the class. Users should inherit from one of these two
1242 classes as appropriate instead.
1243 (Contributed by Brett Cannon in :issue:`42135`.)
1244
1245* The deprecations of :mod:`imp`, :func:`importlib.find_loader`,
1246 :func:`importlib.util.set_package_wrapper`,
1247 :func:`importlib.util.set_loader_wrapper`,
1248 :func:`importlib.util.module_for_loader`,
1249 :class:`pkgutil.ImpImporter`, and
1250 :class:`pkgutil.ImpLoader` have all been updated to list Python 3.12 as the
1251 slated version of removal (they began raising :exc:`DeprecationWarning` in
1252 previous versions of Python).
1253 (Contributed by Brett Cannon in :issue:`43720`.)
1254
Brett Cannon9cb31d62021-03-24 08:26:56 -07001255* The import system now uses the ``__spec__`` attribute on modules before
1256 falling back on :meth:`~importlib.abc.Loader.module_repr` for a module's
1257 ``__repr__()`` method. Removal of the use of ``module_repr()`` is scheduled
1258 for Python 3.12.
1259 (Contributed by Brett Cannon in :issue:`42137`.)
1260
Brett Cannon18990872021-03-26 11:55:07 -07001261* :meth:`importlib.abc.Loader.module_repr`,
1262 :meth:`importlib.machinery.FrozenLoader.module_repr`, and
1263 :meth:`importlib.machinery.BuiltinLoader.module_repr` are deprecated and
1264 slated for removal in Python 3.12.
1265 (Contributed by Brett Cannon in :issue:`42136`.)
1266
Erlend Egeberg Aaslanda1f401a2020-11-17 16:55:12 +01001267* ``sqlite3.OptimizedUnicode`` has been undocumented and obsolete since Python
1268 3.3, when it was made an alias to :class:`str`. It is now deprecated,
1269 scheduled for removal in Python 3.12.
1270 (Contributed by Erlend E. Aasland in :issue:`42264`.)
1271
Erlend Egeberg Aaslandddb5e112021-01-06 01:36:04 +01001272* The undocumented built-in function ``sqlite3.enable_shared_cache`` is now
1273 deprecated, scheduled for removal in Python 3.12. Its use is strongly
1274 discouraged by the SQLite3 documentation. See `the SQLite3 docs
Tom Forbes749d40a2021-02-10 17:56:16 +00001275 <https://sqlite.org/c3ref/enable_shared_cache.html>`_ for more details.
Erlend Egeberg Aaslandddb5e112021-01-06 01:36:04 +01001276 If shared cache must be used, open the database in URI mode using the
1277 ``cache=shared`` query parameter.
1278 (Contributed by Erlend E. Aasland in :issue:`24464`.)
1279
Jelle Zijlstra9825bdf2021-04-12 01:42:53 -07001280* The following ``threading`` methods are now deprecated:
1281
1282 * ``threading.currentThread`` => :func:`threading.current_thread`
1283
1284 * ``threading.activeCount`` => :func:`threading.active_count`
1285
1286 * ``threading.Condition.notifyAll`` =>
1287 :meth:`threading.Condition.notify_all`
1288
1289 * ``threading.Event.isSet`` => :meth:`threading.Event.is_set`
1290
1291 * ``threading.Thread.setName`` => :attr:`threading.Thread.name`
1292
1293 * ``threading.thread.getName`` => :attr:`threading.Thread.name`
1294
1295 * ``threading.Thread.isDaemon`` => :attr:`threading.Thread.daemon`
1296
1297 * ``threading.Thread.setDaemon`` => :attr:`threading.Thread.daemon`
1298
1299 (Contributed by Jelle Zijlstra in :issue:`21574`.)
1300
Pablo Galindod4fe0982020-05-19 03:33:01 +01001301
Pablo Galindod4fe0982020-05-19 03:33:01 +01001302Removed
1303=======
1304
Serhiy Storchakae2ec0b22020-10-09 14:14:37 +03001305* Removed special methods ``__int__``, ``__float__``, ``__floordiv__``,
1306 ``__mod__``, ``__divmod__``, ``__rfloordiv__``, ``__rmod__`` and
1307 ``__rdivmod__`` of the :class:`complex` class. They always raised
1308 a :exc:`TypeError`.
1309 (Contributed by Serhiy Storchaka in :issue:`41974`.)
1310
Berker Peksagd4d127f2020-07-16 09:38:58 +03001311* The ``ParserBase.error()`` method from the private and undocumented ``_markupbase``
1312 module has been removed. :class:`html.parser.HTMLParser` is the only subclass of
1313 ``ParserBase`` and its ``error()`` implementation has already been removed in
1314 Python 3.5.
1315 (Contributed by Berker Peksag in :issue:`31844`.)
1316
Victor Stinner84f73822020-10-27 04:36:22 +01001317* Removed the ``unicodedata.ucnhash_CAPI`` attribute which was an internal
1318 PyCapsule object. The related private ``_PyUnicode_Name_CAPI`` structure was
1319 moved to the internal C API.
1320 (Contributed by Victor Stinner in :issue:`42157`.)
1321
Lysandros Nikolaouc26d5912020-11-16 20:46:37 +02001322* Removed the ``parser`` module, which was deprecated in 3.9 due to the
1323 switch to the new PEG parser, as well as all the C source and header files
1324 that were only being used by the old parser, including ``node.h``, ``parser.h``,
1325 ``graminit.h`` and ``grammar.h``.
1326
1327* Removed the Public C API functions :c:func:`PyParser_SimpleParseStringFlags`,
1328 :c:func:`PyParser_SimpleParseStringFlagsFilename`,
1329 :c:func:`PyParser_SimpleParseFileFlags` and :c:func:`PyNode_Compile`
1330 that were deprecated in 3.9 due to the switch to the new PEG parser.
1331
Dong-hee Nabe319c02020-11-25 22:17:30 +09001332* Removed the ``formatter`` module, which was deprecated in Python 3.4.
1333 It is somewhat obsolete, little used, and not tested. It was originally
1334 scheduled to be removed in Python 3.6, but such removals were delayed until
1335 after Python 2.7 EOL. Existing users should copy whatever classes they use
1336 into their code.
1337 (Contributed by Dong-hee Na and Terry J. Reedy in :issue:`42299`.)
Pablo Galindod4fe0982020-05-19 03:33:01 +01001338
Hai Shi0f91f582020-12-08 22:42:42 +08001339* Removed the :c:func:`PyModule_GetWarningsModule` function that was useless
1340 now due to the _warnings module was converted to a builtin module in 2.6.
1341 (Contributed by Hai Shi in :issue:`42599`.)
1342
Hugo van Kemenadec47c78b2021-01-13 01:16:37 +02001343* Remove deprecated aliases to :ref:`collections-abstract-base-classes` from
1344 the :mod:`collections` module.
1345 (Contributed by Victor Stinner in :issue:`37324`.)
1346
Ken Jindcea78f2021-01-20 16:16:12 -08001347* The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's
1348 :doc:`high-level API <../library/asyncio-api-index>` following deprecation
1349 in Python 3.8. The motivation behind this change is multifold:
1350
1351 1. This simplifies the high-level API.
1352 2. The functions in the high-level API have been implicitly getting the
1353 current thread's running event loop since Python 3.7. There isn't a need to
1354 pass the event loop to the API in most normal use cases.
1355 3. Event loop passing is error-prone especially when dealing with loops
1356 running in different threads.
1357
1358 Note that the low-level API will still accept ``loop``.
1359 See `Changes in the Python API`_ for examples of how to replace existing code.
1360
1361 (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
1362 in :issue:`42392`.)
1363
Hai Shi0f91f582020-12-08 22:42:42 +08001364
Pablo Galindod4fe0982020-05-19 03:33:01 +01001365Porting to Python 3.10
1366======================
1367
1368This section lists previously described changes and other bugfixes
1369that may require changes to your code.
1370
1371
Zackery Spytz91e93792020-11-05 15:18:44 -07001372Changes in the Python API
1373-------------------------
1374
1375* The *etype* parameters of the :func:`~traceback.format_exception`,
1376 :func:`~traceback.format_exception_only`, and
1377 :func:`~traceback.print_exception` functions in the :mod:`traceback` module
1378 have been renamed to *exc*.
1379 (Contributed by Zackery Spytz and Matthias Bussonnier in :issue:`26389`.)
1380
Victor Stinner357704c2020-12-14 23:07:54 +01001381* :mod:`atexit`: At Python exit, if a callback registered with
1382 :func:`atexit.register` fails, its exception is now logged. Previously, only
1383 some exceptions were logged, and the last exception was always silently
1384 ignored.
1385 (Contributed by Victor Stinner in :issue:`42639`.)
1386
kjd75f6f72020-12-19 01:39:26 +08001387* :class:`collections.abc.Callable` generic now flattens type parameters, similar
1388 to what :data:`typing.Callable` currently does. This means that
1389 ``collections.abc.Callable[[int, str], str]`` will have ``__args__`` of
1390 ``(int, str, str)``; previously this was ``([int, str], str)``. Code which
1391 accesses the arguments via :func:`typing.get_args` or ``__args__`` need to account
1392 for this change. Furthermore, :exc:`TypeError` may be raised for invalid forms
1393 of parameterizing :class:`collections.abc.Callable` which may have passed
1394 silently in Python 3.9.
1395 (Contributed by Ken Jin in :issue:`42195`.)
Victor Stinner357704c2020-12-14 23:07:54 +01001396
Erlend Egeberg Aaslandf4936ad2020-12-31 14:16:50 +01001397* :meth:`socket.htons` and :meth:`socket.ntohs` now raise :exc:`OverflowError`
1398 instead of :exc:`DeprecationWarning` if the given parameter will not fit in
1399 a 16-bit unsigned integer.
1400 (Contributed by Erlend E. Aasland in :issue:`42393`.)
1401
Ken Jindcea78f2021-01-20 16:16:12 -08001402* The ``loop`` parameter has been removed from most of :mod:`asyncio`\ 's
1403 :doc:`high-level API <../library/asyncio-api-index>` following deprecation
1404 in Python 3.8.
1405
1406 A coroutine that currently look like this::
1407
1408 async def foo(loop):
1409 await asyncio.sleep(1, loop=loop)
1410
1411 Should be replaced with this::
1412
1413 async def foo():
1414 await asyncio.sleep(1)
1415
1416 If ``foo()`` was specifically designed *not* to run in the current thread's
1417 running event loop (e.g. running in another thread's event loop), consider
1418 using :func:`asyncio.run_coroutine_threadsafe` instead.
1419
1420 (Contributed by Yurii Karabas, Andrew Svetlov, Yury Selivanov and Kyle Stanley
1421 in :issue:`42392`.)
Erlend Egeberg Aaslandf4936ad2020-12-31 14:16:50 +01001422
Victor Stinner46496f92021-02-20 15:17:18 +01001423* The :data:`types.FunctionType` constructor now inherits the current builtins
1424 if the *globals* dictionary has no ``"__builtins__"`` key, rather than using
1425 ``{"None": None}`` as builtins: same behavior as :func:`eval` and
1426 :func:`exec` functions. Defining a function with ``def function(...): ...``
1427 in Python is not affected, globals cannot be overriden with this syntax: it
1428 also inherits the current builtins.
1429 (Contributed by Victor Stinner in :issue:`42990`.)
1430
Yurii Karabas73019792020-11-25 12:43:18 +02001431CPython bytecode changes
1432========================
1433
1434* The ``MAKE_FUNCTION`` instruction accepts tuple of strings as annotations
1435 instead of dictionary.
1436 (Contributed by Yurii Karabas and Inada Naoki in :issue:`42202`)
Dong-hee Naad3252b2020-05-26 01:52:54 +09001437
1438Build Changes
1439=============
1440
Victor Stinner7ab92d52020-06-16 00:54:44 +02001441* The C99 functions :c:func:`snprintf` and :c:func:`vsnprintf` are now required
1442 to build Python.
1443 (Contributed by Victor Stinner in :issue:`36020`.)
1444
Erlend Egeberg Aaslandcf0b2392021-01-06 01:02:43 +01001445* :mod:`sqlite3` requires SQLite 3.7.15 or higher. (Contributed by Sergey Fedoseev
1446 and Erlend E. Aasland :issue:`40744` and :issue:`40810`.)
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001447
Victor Stinner357704c2020-12-14 23:07:54 +01001448* The :mod:`atexit` module must now always be built as a built-in module.
1449 (Contributed by Victor Stinner in :issue:`42639`.)
Erlend Egeberg Aasland207c3212020-09-07 23:26:54 +02001450
Victor Stinner85918e42021-04-12 23:27:35 +02001451* Added :option:`--disable-test-modules` option to the ``configure`` script:
pxinwr277ce302020-12-30 20:50:39 +08001452 don't build nor install test modules.
1453 (Contributed by Xavier de Gaye, Thomas Petazzoni and Peixing Xin in :issue:`27640`.)
1454
Victor Stinner85918e42021-04-12 23:27:35 +02001455* Add :option:`--with-wheel-pkg-dir=PATH option <--with-wheel-pkg-dir>`
1456 to the ``./configure`` script. If
Victor Stinner75e59a92021-01-20 17:07:21 +01001457 specified, the :mod:`ensurepip` module looks for ``setuptools`` and ``pip``
1458 wheel packages in this directory: if both are present, these wheel packages
1459 are used instead of ensurepip bundled wheel packages.
1460
1461 Some Linux distribution packaging policies recommend against bundling
1462 dependencies. For example, Fedora installs wheel packages in the
1463 ``/usr/share/python-wheels/`` directory and don't install the
1464 ``ensurepip._bundled`` package.
1465
1466 (Contributed by Victor Stinner in :issue:`42856`.)
1467
Victor Stinner85918e42021-04-12 23:27:35 +02001468* Add a new :option:`configure --without-static-libpython option
1469 <--without-static-libpython>` to not build the ``libpythonMAJOR.MINOR.a``
1470 static library and not install the ``python.o`` object file.
Victor Stinner801bb0b2021-02-17 11:14:42 +01001471
1472 (Contributed by Victor Stinner in :issue:`43103`.)
1473
Ned Deilya65b0502021-03-01 00:27:20 -05001474* The ``configure`` script now uses the ``pkg-config`` utility, if available,
1475 to detect the location of Tcl/Tk headers and libraries. As before, those
Victor Stinner85918e42021-04-12 23:27:35 +02001476 locations can be explicitly specified with the :option:`--with-tcltk-includes`
1477 and :option:`--with-tcltk-libs` configuration options.
Ned Deilya65b0502021-03-01 00:27:20 -05001478 (Contributed by Manolis Stamatogiannakis in :issue:`42603`.)
1479
Victor Stinner85918e42021-04-12 23:27:35 +02001480* Add :option:`--with-openssl-rpath` option to ``configure`` script. The option
Christian Heimes32eba612021-03-19 10:29:25 +01001481 simplifies building Python with a custom OpenSSL installation, e.g.
1482 ``./configure --with-openssl=/path/to/openssl --with-openssl-rpath=auto``.
1483 (Contributed by Christian Heimes in :issue:`43466`.)
1484
1485
Dong-hee Naad3252b2020-05-26 01:52:54 +09001486
1487C API Changes
1488=============
1489
1490New Features
1491------------
1492
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001493* The result of :c:func:`PyNumber_Index` now always has exact type :class:`int`.
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001494 Previously, the result could have been an instance of a subclass of ``int``.
1495 (Contributed by Serhiy Storchaka in :issue:`40792`.)
1496
Victor Stinnerdd8a93e2020-06-30 00:49:03 +02001497* Add a new :c:member:`~PyConfig.orig_argv` member to the :c:type:`PyConfig`
1498 structure: the list of the original command line arguments passed to the
1499 Python executable.
1500 (Contributed by Victor Stinner in :issue:`23427`.)
Dong-hee Naad3252b2020-05-26 01:52:54 +09001501
Zackery Spytz2e4dd332020-09-23 12:43:45 -06001502* The :c:func:`PyDateTime_DATE_GET_TZINFO` and
1503 :c:func:`PyDateTime_TIME_GET_TZINFO` macros have been added for accessing
1504 the ``tzinfo`` attributes of :class:`datetime.datetime` and
1505 :class:`datetime.time` objects.
1506 (Contributed by Zackery Spytz in :issue:`30155`.)
1507
Hai Shid332e7b2020-09-29 05:41:11 +08001508* Add a :c:func:`PyCodec_Unregister` function to unregister a codec
1509 search function.
1510 (Contributed by Hai Shi in :issue:`41842`.)
1511
Vladimir Matveev24a54c02020-10-12 12:10:42 -07001512* The :c:func:`PyIter_Send` function was added to allow
Vladimir Matveev037245c2020-10-09 17:15:15 -07001513 sending value into iterator without raising ``StopIteration`` exception.
1514 (Contributed by Vladimir Matveev in :issue:`41756`.)
1515
Alex Gaynor3a8fdb22020-10-19 18:17:50 -04001516* Added :c:func:`PyUnicode_AsUTF8AndSize` to the limited C API.
1517 (Contributed by Alex Gaynor in :issue:`41784`.)
1518
Victor Stinner80218752020-11-04 13:59:15 +01001519* Added :c:func:`PyModule_AddObjectRef` function: similar to
Victor Stinner95ce7cd2020-11-11 01:52:26 +01001520 :c:func:`PyModule_AddObject` but don't steal a reference to the value on
Victor Stinner80218752020-11-04 13:59:15 +01001521 success.
1522 (Contributed by Victor Stinner in :issue:`1635741`.)
1523
Victor Stinner53a03aa2020-11-05 15:02:12 +01001524* Added :c:func:`Py_NewRef` and :c:func:`Py_XNewRef` functions to increment the
1525 reference count of an object and return the object.
1526 (Contributed by Victor Stinner in :issue:`42262`.)
1527
Serhiy Storchaka686c2032020-11-22 13:25:02 +02001528* The :c:func:`PyType_FromSpecWithBases` and :c:func:`PyType_FromModuleAndSpec`
1529 functions now accept a single class as the *bases* argument.
1530 (Contributed by Serhiy Storchaka in :issue:`42423`.)
1531
Hai Shi88c2cfd2020-11-07 00:04:47 +08001532* The :c:func:`PyType_FromModuleAndSpec` function now accepts NULL ``tp_doc``
1533 slot.
1534 (Contributed by Hai Shi in :issue:`41832`.)
1535
Hai Shia13b26c2020-11-11 04:53:46 +08001536* The :c:func:`PyType_GetSlot` function can accept static types.
1537 (Contributed by Hai Shi and Petr Viktorin in :issue:`41073`.)
1538
Pablo Galindod439fb32021-02-20 18:03:08 +00001539* Add a new :c:func:`PySet_CheckExact` function to the C-API to check if an
1540 object is an instance of :class:`set` but not an instance of a subtype.
1541 (Contributed by Pablo Galindo in :issue:`43277`.)
Alex Gaynor3a8fdb22020-10-19 18:17:50 -04001542
Antoine Pitrouba251c22021-03-11 23:35:45 +01001543* Added :c:func:`PyErr_SetInterruptEx` which allows passing a signal number
1544 to simulate.
1545 (Contributed by Antoine Pitrou in :issue:`43356`.)
1546
Victor Stinnera41782c2021-04-08 22:32:21 +02001547* The limited C API is now supported if :ref:`Python is built in debug mode
1548 <debug-build>` (if the ``Py_DEBUG`` macro is defined). In the limited C API,
1549 the :c:func:`Py_INCREF` and :c:func:`Py_DECREF` functions are now implemented
1550 as opaque function
Victor Stinner3359cab2021-04-02 15:45:37 +02001551 calls, rather than accessing directly the :c:member:`PyObject.ob_refcnt`
1552 member, if Python is built in debug mode and the ``Py_LIMITED_API`` macro
1553 targets Python 3.10 or newer. It became possible to support the limited C API
1554 in debug mode because the :c:type:`PyObject` structure is the same in release
1555 and debug mode since Python 3.8 (see :issue:`36465`).
1556
Victor Stinner85918e42021-04-12 23:27:35 +02001557 The limited C API is still not supported in the :option:`--with-trace-refs`
1558 special build (``Py_TRACE_REFS`` macro).
Victor Stinner3359cab2021-04-02 15:45:37 +02001559 (Contributed by Victor Stinner in :issue:`43688`.)
Antoine Pitrouba251c22021-03-11 23:35:45 +01001560
Victor Stinner09bbebe2021-04-11 00:17:39 +02001561* Add the :c:func:`Py_Is(x, y) <Py_Is>` function to test if the *x* object is
1562 the *y* object, the same as ``x is y`` in Python. Add also the
1563 :c:func:`Py_IsNone`, :c:func:`Py_IsTrue`, :c:func:`Py_IsFalse` functions to
1564 test if an object is, respectively, the ``None`` singleton, the ``True``
1565 singleton or the ``False`` singleton.
1566 (Contributed by Victor Stinner in :issue:`43753`.)
1567
Dong-hee Naad3252b2020-05-26 01:52:54 +09001568Porting to Python 3.10
1569----------------------
1570
Victor Stinner37bb2892020-06-19 11:45:31 +02001571* The ``PY_SSIZE_T_CLEAN`` macro must now be defined to use
1572 :c:func:`PyArg_ParseTuple` and :c:func:`Py_BuildValue` formats which use
1573 ``#``: ``es#``, ``et#``, ``s#``, ``u#``, ``y#``, ``z#``, ``U#`` and ``Z#``.
1574 See :ref:`Parsing arguments and building values
1575 <arg-parsing>` and the :pep:`353`.
1576 (Contributed by Victor Stinner in :issue:`40943`.)
1577
Victor Stinnerfe2978b2020-05-27 14:55:10 +02001578* Since :c:func:`Py_REFCNT()` is changed to the inline static function,
1579 ``Py_REFCNT(obj) = new_refcnt`` must be replaced with ``Py_SET_REFCNT(obj, new_refcnt)``:
Victor Stinnerdc24b8a2020-06-04 22:10:43 +02001580 see :c:func:`Py_SET_REFCNT()` (available since Python 3.9). For backward
1581 compatibility, this macro can be used::
1582
1583 #if PY_VERSION_HEX < 0x030900A4
1584 # define Py_SET_REFCNT(obj, refcnt) ((Py_REFCNT(obj) = (refcnt)), (void)0)
1585 #endif
1586
Victor Stinnerfe2978b2020-05-27 14:55:10 +02001587 (Contributed by Victor Stinner in :issue:`39573`.)
1588
Victor Stinner59d3dce2020-06-02 14:03:25 +02001589* Calling :c:func:`PyDict_GetItem` without :term:`GIL` held had been allowed
1590 for historical reason. It is no longer allowed.
1591 (Contributed by Victor Stinner in :issue:`40839`.)
1592
Inada Naoki038dd0f2020-06-30 15:26:56 +09001593* ``PyUnicode_FromUnicode(NULL, size)`` and ``PyUnicode_FromStringAndSize(NULL, size)``
1594 raise ``DeprecationWarning`` now. Use :c:func:`PyUnicode_New` to allocate
1595 Unicode object without initial data.
1596 (Contributed by Inada Naoki in :issue:`36346`.)
1597
Victor Stinner47e1afd2020-10-26 16:43:47 +01001598* The private ``_PyUnicode_Name_CAPI`` structure of the PyCapsule API
Victor Stinner84f73822020-10-27 04:36:22 +01001599 ``unicodedata.ucnhash_CAPI`` has been moved to the internal C API.
Victor Stinner920cb642020-10-26 19:19:36 +01001600 (Contributed by Victor Stinner in :issue:`42157`.)
Victor Stinner47e1afd2020-10-26 16:43:47 +01001601
Victor Stinnerace3f9a2020-11-10 21:10:22 +01001602* :c:func:`Py_GetPath`, :c:func:`Py_GetPrefix`, :c:func:`Py_GetExecPrefix`,
1603 :c:func:`Py_GetProgramFullPath`, :c:func:`Py_GetPythonHome` and
1604 :c:func:`Py_GetProgramName` functions now return ``NULL`` if called before
1605 :c:func:`Py_Initialize` (before Python is initialized). Use the new
1606 :ref:`Python Initialization Configuration API <init-config>` to get the
1607 :ref:`Python Path Configuration. <init-path-config>`.
1608 (Contributed by Victor Stinner in :issue:`42260`.)
1609
Victor Stinner0ef96c22020-12-07 11:56:20 +01001610* :c:func:`PyList_SET_ITEM`, :c:func:`PyTuple_SET_ITEM` and
1611 :c:func:`PyCell_SET` macros can no longer be used as l-value or r-value.
1612 For example, ``x = PyList_SET_ITEM(a, b, c)`` and
1613 ``PyList_SET_ITEM(a, b, c) = x`` now fail with a compiler error. It prevents
1614 bugs like ``if (PyList_SET_ITEM (a, b, c) < 0) ...`` test.
1615 (Contributed by Zackery Spytz and Victor Stinner in :issue:`30459`.)
1616
Nicholas Sim4a6bf272021-02-19 22:55:46 +08001617* The non-limited API files ``odictobject.h``, ``parser_interface.h``,
1618 ``picklebufobject.h``, ``pyarena.h``, ``pyctype.h``, ``pydebug.h``,
1619 ``pyfpe.h``, and ``pytime.h`` have been moved to the ``Include/cpython``
1620 directory. These files must not be included directly, as they are already
1621 included in ``Python.h``: :ref:`Include Files <api-includes>`. If they have
1622 been included directly, consider including ``Python.h`` instead.
1623 (Contributed by Nicholas Sim in :issue:`35134`)
1624
Victor Stinner583ee5a2020-10-02 14:49:00 +02001625Deprecated
1626----------
1627
1628* The ``PyUnicode_InternImmortal()`` function is now deprecated
1629 and will be removed in Python 3.12: use :c:func:`PyUnicode_InternInPlace`
1630 instead.
1631 (Contributed by Victor Stinner in :issue:`41692`.)
1632
Dong-hee Naad3252b2020-05-26 01:52:54 +09001633Removed
1634-------
Inada Naoki6f8a6ee2020-06-26 08:07:22 +09001635
1636* ``PyObject_AsCharBuffer()``, ``PyObject_AsReadBuffer()``, ``PyObject_CheckReadBuffer()``,
1637 and ``PyObject_AsWriteBuffer()`` are removed. Please migrate to new buffer protocol;
1638 :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release`.
Inada Naoki20a79022020-06-27 18:22:09 +09001639 (Contributed by Inada Naoki in :issue:`41103`.)
1640
1641* Removed ``Py_UNICODE_str*`` functions manipulating ``Py_UNICODE*`` strings.
1642 (Contributed by Inada Naoki in :issue:`41123`.)
1643
1644 * ``Py_UNICODE_strlen``: use :c:func:`PyUnicode_GetLength` or
1645 :c:macro:`PyUnicode_GET_LENGTH`
1646 * ``Py_UNICODE_strcat``: use :c:func:`PyUnicode_CopyCharacters` or
1647 :c:func:`PyUnicode_FromFormat`
1648 * ``Py_UNICODE_strcpy``, ``Py_UNICODE_strncpy``: use
1649 :c:func:`PyUnicode_CopyCharacters` or :c:func:`PyUnicode_Substring`
1650 * ``Py_UNICODE_strcmp``: use :c:func:`PyUnicode_Compare`
1651 * ``Py_UNICODE_strncmp``: use :c:func:`PyUnicode_Tailmatch`
1652 * ``Py_UNICODE_strchr``, ``Py_UNICODE_strrchr``: use
1653 :c:func:`PyUnicode_FindChar`
Inada Naokid9f2a132020-06-29 10:46:51 +09001654
1655* Removed ``PyUnicode_GetMax()``. Please migrate to new (:pep:`393`) APIs.
1656 (Contributed by Inada Naoki in :issue:`41103`.)
Inada Naokie4f1fe62020-06-29 13:00:43 +09001657
1658* Removed ``PyLong_FromUnicode()``. Please migrate to :c:func:`PyLong_FromUnicodeObject`.
1659 (Contributed by Inada Naoki in :issue:`41103`.)
Inada Naokib3332662020-06-30 12:23:07 +09001660
1661* Removed ``PyUnicode_AsUnicodeCopy()``. Please use :c:func:`PyUnicode_AsUCS4Copy` or
1662 :c:func:`PyUnicode_AsWideCharString`
1663 (Contributed by Inada Naoki in :issue:`41103`.)
Victor Stinner19c3ac92020-09-23 14:04:57 +02001664
1665* Removed ``_Py_CheckRecursionLimit`` variable: it has been replaced by
1666 ``ceval.recursion_limit`` of the :c:type:`PyInterpreterState` structure.
1667 (Contributed by Victor Stinner in :issue:`41834`.)
Serhiy Storchakadcc54212020-10-05 12:32:00 +03001668
1669* Removed undocumented macros ``Py_ALLOW_RECURSION`` and
1670 ``Py_END_ALLOW_RECURSION`` and the ``recursion_critical`` field of the
1671 :c:type:`PyInterpreterState` structure.
1672 (Contributed by Serhiy Storchaka in :issue:`41936`.)
Victor Stinner296a7962020-11-17 16:22:23 +01001673
1674* Removed the undocumented ``PyOS_InitInterrupts()`` function. Initializing
1675 Python already implicitly installs signal handlers: see
1676 :c:member:`PyConfig.install_signal_handlers`.
1677 (Contributed by Victor Stinner in :issue:`41713`.)
Victor Stinnereec8e612021-03-18 14:57:49 +01001678
1679* Remove the ``PyAST_Validate()`` function. It is no longer possible to build a
1680 AST object (``mod_ty`` type) with the public C API. The function was already
1681 excluded from the limited C API (:pep:`384`).
1682 (Contributed by Victor Stinner in :issue:`43244`.)
Victor Stinner28ad12f2021-03-19 12:41:49 +01001683
1684* Remove the ``symtable.h`` header file and the undocumented functions:
1685
1686 * ``PyST_GetScope()``
1687 * ``PySymtable_Build()``
1688 * ``PySymtable_BuildObject()``
1689 * ``PySymtable_Free()``
1690 * ``Py_SymtableString()``
1691 * ``Py_SymtableStringObject()``
1692
1693 The ``Py_SymtableString()`` function was part the stable ABI by mistake but
1694 it could not be used, because the ``symtable.h`` header file was excluded
1695 from the limited C API.
1696
Victor Stinner94faa072021-03-23 20:47:40 +01001697 Use Python :mod:`symtable` module instead.
1698 (Contributed by Victor Stinner in :issue:`43244`.)
1699
1700* Remove ``ast.h``, ``asdl.h``, and ``Python-ast.h`` header files.
1701 These functions were undocumented and excluded from the limited C API.
1702 Most names defined by these header files were not prefixed by ``Py`` and so
1703 could create names conflicts. For example, ``Python-ast.h`` defined a
1704 ``Yield`` macro which was conflict with the ``Yield`` name used by the
1705 Windows ``<winbase.h>`` header. Use the Python :mod:`ast` module instead.
Victor Stinner28ad12f2021-03-19 12:41:49 +01001706 (Contributed by Victor Stinner in :issue:`43244`.)
Victor Stinnera81fca62021-03-24 00:51:50 +01001707
Victor Stinner57364ce2021-03-24 01:29:09 +01001708* Remove the compiler and parser functions using ``struct _mod`` type, because
1709 the public AST C API was removed:
Victor Stinnera81fca62021-03-24 00:51:50 +01001710
1711 * ``PyAST_Compile()``
1712 * ``PyAST_CompileEx()``
1713 * ``PyAST_CompileObject()``
1714 * ``PyFuture_FromAST()``
1715 * ``PyFuture_FromASTObject()``
Victor Stinner57364ce2021-03-24 01:29:09 +01001716 * ``PyParser_ASTFromFile()``
1717 * ``PyParser_ASTFromFileObject()``
1718 * ``PyParser_ASTFromFilename()``
1719 * ``PyParser_ASTFromString()``
1720 * ``PyParser_ASTFromStringObject()``
Victor Stinnera81fca62021-03-24 00:51:50 +01001721
1722 These functions were undocumented and excluded from the limited C API.
1723 (Contributed by Victor Stinner in :issue:`43244`.)
Victor Stinner8370e072021-03-24 02:23:01 +01001724
1725* Remove the ``pyarena.h`` header file with functions:
1726
1727 * ``PyArena_New()``
1728 * ``PyArena_Free()``
1729 * ``PyArena_Malloc()``
1730 * ``PyArena_AddPyObject()``
1731
1732 These functions were undocumented, excluded from the limited C API, and were
1733 only used internally by the compiler.
1734 (Contributed by Victor Stinner in :issue:`43244`.)