Debian Codegraph @

Doc/whatsnew/3.13.rst

raw
1
2 ****************************
3 What's New In Python 3.13
4 ****************************
5
6 :Editors: Adam Turner and Thomas Wouters
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 issue number as a comment:
40
41 XXX Describe the transmogrify() function added to the socket
42 module.
43 (Contributed by P.Y. Developer in :gh:`12345`.)
44
45 This saves the maintainer the effort of going through the VCS log
46 when researching a change.
47
48 This article explains the new features in Python 3.13, compared to 3.12.
49 Python 3.13 was released on October 7, 2024.
50 For full details, see the :ref:`changelog <changelog>`.
51
52 .. seealso::
53
54 :pep:`719` -- Python 3.13 Release Schedule
55
56
57 Summary -- Release Highlights
58 =============================
59
60 .. This section singles out the most important changes in Python 3.13.
61 Brevity is key.
62
63 Python 3.13 is the latest stable release of the Python programming
64 language, with a mix of changes to the language, the implementation
65 and the standard library.
66 The biggest changes include a new `interactive interpreter
67 <whatsnew313-better-interactive-interpreter_>`_,
68 experimental support for running in a `free-threaded mode
69 <whatsnew313-free-threaded-cpython_>`_ (:pep:`703`),
70 and a `Just-In-Time compiler <whatsnew313-jit-compiler_>`_ (:pep:`744`).
71
72 Error messages continue to improve, with tracebacks now highlighted in color
73 by default. The :func:`locals` builtin now has :ref:`defined semantics
74 <whatsnew313-locals-semantics>` for changing the returned mapping,
75 and type parameters now support default values.
76
77 The library changes contain removal of deprecated APIs and modules,
78 as well as the usual improvements in user-friendliness and correctness.
79 Several legacy standard library modules have now `been removed
80 <whatsnew313-pep594_>`_ following their deprecation in Python 3.11 (:pep:`594`).
81
82 This article doesn't attempt to provide a complete specification
83 of all new features, but instead gives a convenient overview.
84 For full details refer to the documentation,
85 such as the :ref:`Library Reference <library-index>`
86 and :ref:`Language Reference <reference-index>`.
87 To understand the complete implementation and design rationale for a change,
88 refer to the PEP for a particular new feature;
89 but note that PEPs usually are not kept up-to-date
90 once a feature has been fully implemented.
91 See `Porting to Python 3.13`_ for guidance on upgrading from
92 earlier versions of Python.
93
94 --------------
95
96 .. PEP-sized items next.
97
98 Interpreter improvements:
99
100 * A greatly improved :ref:`interactive interpreter
101 <whatsnew313-better-interactive-interpreter>` and
102 :ref:`improved error messages <whatsnew313-improved-error-messages>`.
103 * :pep:`667`: The :func:`locals` builtin now has
104 :ref:`defined semantics <whatsnew313-locals-semantics>` when mutating the
105 returned mapping. Python debuggers and similar tools may now more reliably
106 update local variables in optimized scopes even during concurrent code
107 execution.
108 * :pep:`703`: CPython 3.13 has experimental support for running with the
109 :term:`global interpreter lock` disabled. See :ref:`Free-threaded CPython
110 <whatsnew313-free-threaded-cpython>` for more details.
111 * :pep:`744`: A basic :ref:`JIT compiler <whatsnew313-jit-compiler>` was added.
112 It is currently disabled by default (though we may turn it on later).
113 Performance improvements are modest -- we expect to improve this
114 over the next few releases.
115 * Color support in the new :ref:`interactive interpreter
116 <whatsnew313-better-interactive-interpreter>`,
117 as well as in :ref:`tracebacks <whatsnew313-improved-error-messages>`
118 and :ref:`doctest <whatsnew313-doctest>` output.
119 This can be disabled through the :envvar:`PYTHON_COLORS` and |NO_COLOR|_
120 environment variables.
121
122 Python data model improvements:
123
124 * :attr:`~type.__static_attributes__` stores the names of attributes accessed
125 through ``self.X`` in any function in a class body.
126 * :attr:`~type.__firstlineno__` records the first line number of a class
127 definition.
128
129 Significant improvements in the standard library:
130
131 * Add a new :exc:`PythonFinalizationError` exception, raised when an operation
132 is blocked during :term:`finalization <interpreter shutdown>`.
133 * The :mod:`argparse` module now supports deprecating command-line options,
134 positional arguments, and subcommands.
135 * The new functions :func:`base64.z85encode` and :func:`base64.z85decode`
136 support encoding and decoding `Z85 data`_.
137 * The :mod:`copy` module now has a :func:`copy.replace` function,
138 with support for many builtin types and any class defining
139 the :func:`~object.__replace__` method.
140 * The new :mod:`dbm.sqlite3` module is now the default :mod:`dbm` backend.
141 * The :mod:`os` module has a :ref:`suite of new functions <os-timerfd>`
142 for working with Linux's timer notification file descriptors.
143 * The :mod:`random` module now has a :ref:`command-line interface <random-cli>`.
144
145 Security improvements:
146
147 * :func:`ssl.create_default_context` sets :data:`ssl.VERIFY_X509_PARTIAL_CHAIN`
148 and :data:`ssl.VERIFY_X509_STRICT` as default flags.
149
150 C API improvements:
151
152 * The :c:data:`Py_mod_gil` slot is now used to indicate that
153 an extension module supports running with the :term:`GIL` disabled.
154 * The :doc:`PyTime C API </c-api/time>` has been added,
155 providing access to system clocks.
156 * :c:type:`PyMutex` is a new lightweight mutex that occupies a single byte.
157 * There is a new :ref:`suite of functions <c-api-monitoring>`
158 for generating :pep:`669` monitoring events in the C API.
159
160 New typing features:
161
162 * :pep:`696`: Type parameters (:data:`typing.TypeVar`, :data:`typing.ParamSpec`,
163 and :data:`typing.TypeVarTuple`) now support defaults.
164 * :pep:`702`: The new :func:`warnings.deprecated` decorator adds support
165 for marking deprecations in the type system and at runtime.
166 * :pep:`705`: :data:`typing.ReadOnly` can be used to mark an item of a
167 :class:`typing.TypedDict` as read-only for type checkers.
168 * :pep:`742`: :data:`typing.TypeIs` provides more intuitive
169 type narrowing behavior, as an alternative to :data:`typing.TypeGuard`.
170
171 Platform support:
172
173 * :pep:`730`: Apple's iOS is now an :ref:`officially supported platform
174 <whatsnew313-platform-support>`, at :pep:`tier 3 <11#tier-3>`.
175 * :pep:`738`: Android is now an :ref:`officially supported platform
176 <whatsnew313-platform-support>`, at :pep:`tier 3 <11#tier-3>`.
177 * ``wasm32-wasi`` is now supported as a :pep:`tier 2 <11#tier-2>` platform.
178 * ``wasm32-emscripten`` is no longer an officially supported platform.
179
180 Important removals:
181
182 * :ref:`PEP 594 <whatsnew313-pep594>`: The remaining 19 "dead batteries"
183 (legacy stdlib modules) have been removed from the standard library:
184 :mod:`!aifc`, :mod:`!audioop`, :mod:`!cgi`, :mod:`!cgitb`, :mod:`!chunk`,
185 :mod:`!crypt`, :mod:`!imghdr`, :mod:`!mailcap`, :mod:`!msilib`, :mod:`!nis`,
186 :mod:`!nntplib`, :mod:`!ossaudiodev`, :mod:`!pipes`, :mod:`!sndhdr`,
187 :mod:`!spwd`, :mod:`!sunau`, :mod:`!telnetlib`, :mod:`!uu` and :mod:`!xdrlib`.
188 * Remove the :program:`2to3` tool and :mod:`!lib2to3` module
189 (deprecated in Python 3.11).
190 * Remove the :mod:`!tkinter.tix` module (deprecated in Python 3.6).
191 * Remove the :func:`!locale.resetlocale` function.
192 * Remove the :mod:`!typing.io` and :mod:`!typing.re` namespaces.
193 * Remove chained :class:`classmethod` descriptors.
194
195 Release schedule changes:
196
197 :pep:`602` ("Annual Release Cycle for Python") has been updated
198 to extend the full support ('bugfix') period for new releases to two years.
199 This updated policy means that:
200
201 * Python 3.9--3.12 have one and a half years of full support,
202 followed by three and a half years of security fixes.
203 * Python 3.13 and later have two years of full support,
204 followed by three years of security fixes.
205
206
207 New Features
208 ============
209
210
211 .. _whatsnew313-better-interactive-interpreter:
212
213 A better interactive interpreter
214 --------------------------------
215
216 Python now uses a new :term:`interactive` shell by default, based on code
217 from the `PyPy project`_.
218 When the user starts the :term:`REPL` from an interactive terminal,
219 the following new features are now supported:
220
221 * Multiline editing with history preservation.
222 * Direct support for REPL-specific commands like :kbd:`help`, :kbd:`exit`,
223 and :kbd:`quit`, without the need to call them as functions.
224 * Prompts and tracebacks with :ref:`color enabled by default
225 <using-on-controlling-color>`.
226 * Interactive help browsing using :kbd:`F1` with a separate command
227 history.
228 * History browsing using :kbd:`F2` that skips output as well as the
229 :term:`>>>` and :term:`...` prompts.
230 * "Paste mode" with :kbd:`F3` that makes pasting larger blocks of code
231 easier (press :kbd:`F3` again to return to the regular prompt).
232
233 To disable the new interactive shell,
234 set the :envvar:`PYTHON_BASIC_REPL` environment variable.
235 For more on interactive mode, see :ref:`tut-interac`.
236
237 (Contributed by Pablo Galindo Salgado, Łukasz Langa, and
238 Lysandros Nikolaou in :gh:`111201` based on code from the PyPy project.
239 Windows support contributed by Dino Viehland and Anthony Shaw.)
240
241 .. _`PyPy project`: https://pypy.org/
242
243
244 .. _whatsnew313-improved-error-messages:
245
246 Improved error messages
247 -----------------------
248
249 * The interpreter now uses color by default when displaying tracebacks in the
250 terminal. This feature :ref:`can be controlled <using-on-controlling-color>`
251 via the new :envvar:`PYTHON_COLORS` environment variable as well as
252 the canonical |NO_COLOR|_ and |FORCE_COLOR|_ environment variables.
253 (Contributed by Pablo Galindo Salgado in :gh:`112730`.)
254
255 .. Apparently this how you hack together a formatted link:
256 (https://www.docutils.org/docs/ref/rst/directives.html#replacement-text)
257
258 .. |FORCE_COLOR| replace:: ``FORCE_COLOR``
259 .. _FORCE_COLOR: https://force-color.org/
260
261 .. |NO_COLOR| replace:: ``NO_COLOR``
262 .. _NO_COLOR: https://no-color.org/
263
264 * A common mistake is to write a script with the same name as a
265 standard library module. When this results in errors, we now
266 display a more helpful error message:
267
268 .. code-block:: pytb
269
270 $ python random.py
271 Traceback (most recent call last):
272 File "/home/me/random.py", line 1, in <module>
273 import random
274 File "/home/me/random.py", line 3, in <module>
275 print(random.randint(5))
276 ^^^^^^^^^^^^^^
277 AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/random.py' since it has the same name as the standard library module named 'random' and prevents importing that standard library module)
278
279 Similarly, if a script has the same name as a third-party
280 module that it attempts to import and this results in errors,
281 we also display a more helpful error message:
282
283 .. code-block:: pytb
284
285 $ python numpy.py
286 Traceback (most recent call last):
287 File "/home/me/numpy.py", line 1, in <module>
288 import numpy as np
289 File "/home/me/numpy.py", line 3, in <module>
290 np.array([1, 2, 3])
291 ^^^^^^^^
292 AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/home/me/numpy.py' if it has the same name as a library you intended to import)
293
294 (Contributed by Shantanu Jain in :gh:`95754`.)
295
296 * The error message now tries to suggest the correct keyword argument
297 when an incorrect keyword argument is passed to a function.
298
299 .. code-block:: pycon
300
301 >>> "Better error messages!".split(max_split=1)
302 Traceback (most recent call last):
303 File "<python-input-0>", line 1, in <module>
304 "Better error messages!".split(max_split=1)
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
306 TypeError: split() got an unexpected keyword argument 'max_split'. Did you mean 'maxsplit'?
307
308 (Contributed by Pablo Galindo Salgado and Shantanu Jain in :gh:`107944`.)
309
310
311 .. _whatsnew313-free-threaded-cpython:
312
313 Free-threaded CPython
314 ---------------------
315
316 CPython now has experimental support for running in a free-threaded mode,
317 with the :term:`global interpreter lock` (GIL) disabled.
318 This is an experimental feature and therefore is not enabled by default.
319 The free-threaded mode requires a different executable,
320 usually called ``python3.13t`` or ``python3.13t.exe``.
321 Pre-built binaries marked as *free-threaded* can be installed as part of
322 the official :ref:`Windows <install-freethreaded-windows>`
323 and :ref:`macOS <install-freethreaded-macos>` installers,
324 or CPython can be built from source with the :option:`--disable-gil` option.
325
326 Free-threaded execution allows for full utilization of the available
327 processing power by running threads in parallel on available CPU cores.
328 While not all software will benefit from this automatically, programs
329 designed with threading in mind will run faster on multi-core hardware.
330 **The free-threaded mode is experimental** and work is ongoing to improve it:
331 expect some bugs and a substantial single-threaded performance hit.
332 Free-threaded builds of CPython support optionally running with the GIL
333 enabled at runtime using the environment variable :envvar:`PYTHON_GIL` or
334 the command-line option :option:`-X gil=1`.
335
336 To check if the current interpreter supports free-threading, :option:`python -VV <-V>`
337 and :data:`sys.version` contain "experimental free-threading build".
338 The new :func:`!sys._is_gil_enabled` function can be used to check whether
339 the GIL is actually disabled in the running process.
340
341 C-API extension modules need to be built specifically for the free-threaded
342 build. Extensions that support running with the :term:`GIL` disabled should
343 use the :c:data:`Py_mod_gil` slot. Extensions using single-phase init should
344 use :c:func:`PyUnstable_Module_SetGIL` to indicate whether they support
345 running with the GIL disabled. Importing C extensions that don't use these
346 mechanisms will cause the GIL to be enabled, unless the GIL was explicitly
347 disabled with the :envvar:`PYTHON_GIL` environment variable or the
348 :option:`-X gil=0` option.
349 pip 24.1 or newer is required to install packages with C extensions in the
350 free-threaded build.
351
352 This work was made possible thanks to many individuals and
353 organizations, including the large community of contributors to Python
354 and third-party projects to test and enable free-threading support.
355 Notable contributors include:
356 Sam Gross, Ken Jin, Donghee Na, Itamar Oren, Matt Page, Brett Simmers,
357 Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf Gommers,
358 Lysandros Nikolaou, and many others.
359 Many of these contributors are employed by Meta, which has
360 provided significant engineering resources to support this project.
361
362 .. seealso::
363
364 :pep:`703` "Making the Global Interpreter Lock Optional in CPython"
365 contains rationale and information surrounding this work.
366
367 `Porting Extension Modules to Support Free-Threading
368 <https://py-free-threading.github.io/porting/>`_: A community-maintained
369 porting guide for extension authors.
370
371
372 .. _whatsnew313-jit-compiler:
373
374 An experimental just-in-time (JIT) compiler
375 -------------------------------------------
376
377 When CPython is configured and built using
378 the :option:`!--enable-experimental-jit` option,
379 a just-in-time (JIT) compiler is added which may speed up some Python programs.
380 On Windows, use ``PCbuild/build.bat --experimental-jit`` to enable the JIT
381 or ``--experimental-jit-interpreter`` to enable the Tier 2 interpreter.
382 Build requirements and further supporting information `are contained at`__
383 :file:`Tools/jit/README.md`.
384
385 __ https://github.com/python/cpython/blob/main/Tools/jit/README.md
386
387 The :option:`!--enable-experimental-jit` option takes these (optional) values,
388 defaulting to ``yes`` if :option:`!--enable-experimental-jit` is present
389 without the optional value.
390
391 * ``no``: Disable the entire Tier 2 and JIT pipeline.
392 * ``yes``: Enable the JIT.
393 To disable the JIT at runtime, pass the environment variable :envvar:`PYTHON_JIT=0 <PYTHON_JIT>`.
394 * ``yes-off``: Build the JIT but disable it by default.
395 To enable the JIT at runtime, pass the environment variable :envvar:`PYTHON_JIT=1 <PYTHON_JIT>`.
396 * ``interpreter``: Enable the Tier 2 interpreter but disable the JIT.
397 The interpreter can be disabled by running with :envvar:`PYTHON_JIT=0 <PYTHON_JIT>`.
398
399 The internal architecture is roughly as follows:
400
401 * We start with specialized *Tier 1 bytecode*.
402 See :ref:`What's new in 3.11 <whatsnew311-pep659>` for details.
403 * When the Tier 1 bytecode gets hot enough, it gets translated
404 to a new purely internal intermediate representation (IR),
405 called the *Tier 2 IR*, and sometimes referred to as micro-ops ("uops").
406 * The Tier 2 IR uses the same stack-based virtual machine as Tier 1,
407 but the instruction format is better suited to translation to machine code.
408 * We have several optimization passes for Tier 2 IR, which are applied
409 before it is interpreted or translated to machine code.
410 * There is a Tier 2 interpreter, but it is mostly intended for debugging
411 the earlier stages of the optimization pipeline.
412 The Tier 2 interpreter can be enabled by configuring Python
413 with ``--enable-experimental-jit=interpreter``.
414 * When the JIT is enabled, the optimized
415 Tier 2 IR is translated to machine code, which is then executed.
416 * The machine code translation process uses a technique called
417 *copy-and-patch*. It has no runtime dependencies, but there is a new
418 build-time dependency on LLVM.
419
420 .. seealso:: :pep:`744`
421
422 (JIT by Brandt Bucher, inspired by a paper by Haoran Xu and Fredrik Kjolstad.
423 Tier 2 IR by Mark Shannon and Guido van Rossum.
424 Tier 2 optimizer by Ken Jin.)
425
426
427 .. _whatsnew313-locals-semantics:
428
429 Defined mutation semantics for :py:func:`locals`
430 ------------------------------------------------
431
432 Historically, the expected result of mutating the return value of
433 :func:`locals` has been left to individual Python implementations to define.
434 Starting from Python 3.13, :pep:`667` standardises
435 the historical behavior of CPython for most code execution scopes,
436 but changes :term:`optimized scopes <optimized scope>`
437 (functions, generators, coroutines, comprehensions, and generator expressions)
438 to explicitly return independent snapshots of the currently assigned local
439 variables, including locally referenced nonlocal variables captured in closures.
440
441 This change to the semantics of :func:`locals` in optimized scopes also
442 affects the default behavior of code execution functions that implicitly
443 target :func:`!locals` if no explicit namespace is provided
444 (such as :func:`exec` and :func:`eval`).
445 In previous versions, whether or not changes could be accessed by calling
446 :func:`!locals` after calling the code execution function was
447 implementation-dependent. In CPython specifically, such code would typically
448 appear to work as desired, but could sometimes fail in optimized scopes based
449 on other code (including debuggers and code execution tracing tools)
450 potentially resetting the shared snapshot in that scope.
451 Now, the code will always run against an independent snapshot of
452 the local variables in optimized scopes, and hence the changes will never
453 be visible in subsequent calls to :func:`!locals`.
454 To access the changes made in these cases, an explicit namespace reference
455 must now be passed to the relevant function.
456 Alternatively, it may make sense to update affected code to use a higher level
457 code execution API that returns the resulting code execution namespace
458 (e.g. :func:`runpy.run_path` when executing Python files from disk).
459
460 To ensure debuggers and similar tools can reliably update local variables in
461 scopes affected by this change, :attr:`FrameType.f_locals <frame.f_locals>` now
462 returns a write-through proxy to the frame's local and locally referenced
463 nonlocal variables in these scopes, rather than returning an inconsistently
464 updated shared ``dict`` instance with undefined runtime semantics.
465
466 See :pep:`667` for more details, including related C API changes
467 and deprecations. Porting notes are also provided below for the affected
468 :ref:`Python APIs <pep667-porting-notes-py>` and :ref:`C APIs
469 <pep667-porting-notes-c>`.
470
471 (PEP and implementation contributed by Mark Shannon and Tian Gao in
472 :gh:`74929`. Documentation updates provided by Guido van Rossum and
473 Alyssa Coghlan.)
474
475
476 .. _whatsnew313-platform-support:
477
478 Support for mobile platforms
479 ----------------------------
480
481 :pep:`730`: iOS is now a :pep:`11` supported platform, with the
482 ``arm64-apple-ios`` and ``arm64-apple-ios-simulator`` targets at tier 3
483 (iPhone and iPad devices released after 2013 and the Xcode iOS simulator
484 running on Apple silicon hardware, respectively).
485 ``x86_64-apple-ios-simulator``
486 (the Xcode iOS simulator running on older ``x86_64`` hardware)
487 is not a tier 3 supported platform, but will have best-effort support.
488 (PEP written and implementation contributed by Russell Keith-Magee in
489 :gh:`114099`.)
490
491 :pep:`738`: Android is now a :pep:`11` supported platform, with the
492 ``aarch64-linux-android`` and ``x86_64-linux-android`` targets at tier 3.
493 The 32-bit targets ``arm-linux-androideabi`` and ``i686-linux-android``
494 are not tier 3 supported platforms, but will have best-effort support.
495 (PEP written and implementation contributed by Malcolm Smith in
496 :gh:`116622`.)
497
498 .. seealso:: :pep:`730`, :pep:`738`
499
500
501 Other Language Changes
502 ======================
503
504 * The compiler now strips common leading whitespace
505 from every line in a docstring.
506 This reduces the size of the :term:`bytecode cache <bytecode>`
507 (such as ``.pyc`` files), with reductions in file size of around 5%,
508 for example in :mod:`!sqlalchemy.orm.session` from SQLAlchemy 2.0.
509 This change affects tools that use docstrings, such as :mod:`doctest`.
510
511 .. doctest::
512
513 >>> def spam():
514 ... """
515 ... This is a docstring with
516 ... leading whitespace.
517 ...
518 ... It even has multiple paragraphs!
519 ... """
520 ...
521 >>> spam.__doc__
522 '\nThis is a docstring with\n leading whitespace.\n\nIt even has multiple paragraphs!\n'
523
524 (Contributed by Inada Naoki in :gh:`81283`.)
525
526 * :ref:`Annotation scopes <annotation-scopes>` within class scopes
527 can now contain lambdas and comprehensions.
528 Comprehensions that are located within class scopes
529 are not inlined into their parent scope.
530
531 .. code-block:: python
532
533 class C[T]:
534 type Alias = lambda: T
535
536 (Contributed by Jelle Zijlstra in :gh:`109118` and :gh:`118160`.)
537
538 * :ref:`Future statements <future>` are no longer triggered by
539 relative imports of the :mod:`__future__` module,
540 meaning that statements of the form ``from .__future__ import ...``
541 are now simply standard relative imports, with no special features activated.
542 (Contributed by Jeremiah Gabriel Pascual in :gh:`118216`.)
543
544 * :keyword:`global` declarations are now permitted in :keyword:`except` blocks
545 when that global is used in the :keyword:`else` block.
546 Previously this raised an erroneous :exc:`SyntaxError`.
547 (Contributed by Irit Katriel in :gh:`111123`.)
548
549 * Add :envvar:`PYTHON_FROZEN_MODULES`, a new environment variable that
550 determines whether frozen modules are ignored by the import machinery,
551 equivalent to the :option:`-X frozen_modules <-X>` command-line option.
552 (Contributed by Yilei Yang in :gh:`111374`.)
553
554 * Add :ref:`support for the perf profiler <perf_profiling>` working
555 without `frame pointers <https://en.wikipedia.org/wiki/Call_stack>`_ through
556 the new environment variable :envvar:`PYTHON_PERF_JIT_SUPPORT`
557 and command-line option :option:`-X perf_jit <-X>`.
558 (Contributed by Pablo Galindo in :gh:`118518`.)
559
560 * The location of a :file:`.python_history` file can be changed via the
561 new :envvar:`PYTHON_HISTORY` environment variable.
562 (Contributed by Levi Sabah, Zackery Spytz and Hugo van Kemenade
563 in :gh:`73965`.)
564
565 * Classes have a new :attr:`~type.__static_attributes__` attribute.
566 This is populated by the compiler with a tuple of the class's attribute names
567 which are assigned through ``self.<name>`` from any function in its body.
568 (Contributed by Irit Katriel in :gh:`115775`.)
569
570 * The compiler now creates a :attr:`!__firstlineno__` attribute on classes
571 with the line number of the first line of the class definition.
572 (Contributed by Serhiy Storchaka in :gh:`118465`.)
573
574 * The :func:`exec` and :func:`eval` builtins now accept
575 the *globals* and *locals* arguments as keywords.
576 (Contributed by Raphael Gaschignard in :gh:`105879`)
577
578 * The :func:`compile` builtin now accepts a new flag,
579 ``ast.PyCF_OPTIMIZED_AST``, which is similar to ``ast.PyCF_ONLY_AST``
580 except that the returned AST is optimized according to
581 the value of the *optimize* argument.
582 (Contributed by Irit Katriel in :gh:`108113`).
583
584 * Add a :attr:`~property.__name__` attribute on :class:`property` objects.
585 (Contributed by Eugene Toder in :gh:`101860`.)
586
587 * Add :exc:`PythonFinalizationError`, a new exception derived from
588 :exc:`RuntimeError` and used to signal when operations are blocked
589 during :term:`finalization <interpreter shutdown>`.
590 The following callables now raise :exc:`!PythonFinalizationError`,
591 instead of :exc:`RuntimeError`:
592
593 * :func:`_thread.start_new_thread`
594 * :func:`os.fork`
595 * :func:`os.forkpty`
596 * :class:`subprocess.Popen`
597
598 (Contributed by Victor Stinner in :gh:`114570`.)
599
600 * Allow the *count* argument of :meth:`str.replace` to be a keyword.
601 (Contributed by Hugo van Kemenade in :gh:`106487`.)
602
603 * Many functions now emit a warning if a boolean value is passed as
604 a file descriptor argument.
605 This can help catch some errors earlier.
606 (Contributed by Serhiy Storchaka in :gh:`82626`.)
607
608 * Added :attr:`!name` and :attr:`!mode` attributes
609 for compressed and archived file-like objects in
610 the :mod:`bz2`, :mod:`lzma`, :mod:`tarfile`, and :mod:`zipfile` modules.
611 (Contributed by Serhiy Storchaka in :gh:`115961`.)
612
613
614 New Modules
615 ===========
616
617 * :mod:`dbm.sqlite3`: An SQLite backend for :mod:`dbm`.
618 (Contributed by Raymond Hettinger and Erlend E. Aasland in :gh:`100414`.)
619
620
621 Improved Modules
622 ================
623
624
625 argparse
626 --------
627
628 * Add the *deprecated* parameter to the
629 :meth:`~argparse.ArgumentParser.add_argument`
630 and :meth:`!add_parser` methods, to enable deprecating
631 command-line options, positional arguments, and subcommands.
632 (Contributed by Serhiy Storchaka in :gh:`83648`.)
633
634
635 array
636 -----
637
638 * Add the ``'w'`` type code (``Py_UCS4``) for Unicode characters.
639 It should be used instead of the deprecated ``'u'`` type code.
640 (Contributed by Inada Naoki in :gh:`80480`.)
641
642 * Register :class:`array.array` as a :class:`~collections.abc.MutableSequence`
643 by implementing the :meth:`~array.array.clear` method.
644 (Contributed by Mike Zimin in :gh:`114894`.)
645
646
647 ast
648 ---
649
650 * The constructors of node types in the :mod:`ast` module are now
651 stricter in the arguments they accept,
652 with more intuitive behavior when arguments are omitted.
653
654 If an optional field on an AST node is not included as an argument when
655 constructing an instance, the field will now be set to ``None``. Similarly,
656 if a list field is omitted, that field will now be set to an empty list,
657 and if an :class:`!expr_context` field is omitted, it defaults to
658 :class:`Load() <ast.Load>`.
659 (Previously, in all cases, the attribute would be missing on the newly
660 constructed AST node instance.)
661
662 In all other cases, where a required argument is omitted,
663 the node constructor will emit a :exc:`DeprecationWarning`.
664 This will raise an exception in Python 3.15.
665 Similarly, passing a keyword argument to the constructor
666 that does not map to a field on the AST node is now deprecated,
667 and will raise an exception in Python 3.15.
668
669 These changes do not apply to user-defined subclasses of :class:`ast.AST`
670 unless the class opts in to the new behavior
671 by defining the :attr:`.AST._field_types` mapping.
672
673 (Contributed by Jelle Zijlstra in :gh:`105858`, :gh:`117486`, and :gh:`118851`.)
674
675 * :func:`ast.parse` now accepts an optional argument *optimize*
676 which is passed on to :func:`compile`.
677 This makes it possible to obtain an optimized AST.
678 (Contributed by Irit Katriel in :gh:`108113`.)
679
680
681 asyncio
682 -------
683
684 * :func:`asyncio.as_completed` now returns an object that is both an
685 :term:`asynchronous iterator` and a plain :term:`iterator`
686 of :term:`awaitables <awaitable>`.
687 The awaitables yielded by asynchronous iteration include original task
688 or future objects that were passed in,
689 making it easier to associate results with the tasks being completed.
690 (Contributed by Justin Arthur in :gh:`77714`.)
691
692 * :meth:`asyncio.loop.create_unix_server` will now automatically remove
693 the Unix socket when the server is closed.
694 (Contributed by Pierre Ossman in :gh:`111246`.)
695
696 * :meth:`.DatagramTransport.sendto` will now send zero-length
697 datagrams if called with an empty bytes object.
698 The transport flow control also now accounts for the datagram header
699 when calculating the buffer size.
700 (Contributed by Jamie Phan in :gh:`115199`.)
701
702 * Add :meth:`Queue.shutdown <asyncio.Queue.shutdown>`
703 and :exc:`~asyncio.QueueShutDown` to manage queue termination.
704 (Contributed by Laurie Opperman and Yves Duprat in :gh:`104228`.)
705
706 * Add the :meth:`.Server.close_clients` and :meth:`.Server.abort_clients`
707 methods, which more forcefully close an asyncio server.
708 (Contributed by Pierre Ossman in :gh:`113538`.)
709
710 * Accept a tuple of separators in :meth:`.StreamReader.readuntil`,
711 stopping when any one of them is encountered.
712 (Contributed by Bruce Merry in :gh:`81322`.)
713
714 * Improve the behavior of :class:`~asyncio.TaskGroup` when
715 an external cancellation collides with an internal cancellation.
716 For example, when two task groups are nested
717 and both experience an exception in a child task simultaneously,
718 it was possible that the outer task group would hang,
719 because its internal cancellation was swallowed by the inner task group.
720
721 In the case where a task group is cancelled externally
722 and also must raise an :exc:`ExceptionGroup`,
723 it will now call the parent task's :meth:`~asyncio.Task.cancel` method.
724 This ensures that a :exc:`~asyncio.CancelledError` will be raised
725 at the next :keyword:`await`, so the cancellation is not lost.
726
727 An added benefit of these changes is that task groups now preserve
728 the cancellation count (:meth:`~asyncio.Task.cancelling`).
729
730 In order to handle some corner cases, :meth:`~asyncio.Task.uncancel` may now
731 reset the undocumented ``_must_cancel`` flag
732 when the cancellation count reaches zero.
733
734 (Inspired by an issue reported by Arthur Tacca in :gh:`116720`.)
735
736 * When :meth:`.TaskGroup.create_task` is called on an inactive
737 :class:`~asyncio.TaskGroup`, the given coroutine will be closed (which
738 prevents a :exc:`RuntimeWarning` about the given coroutine being
739 never awaited).
740 (Contributed by Arthur Tacca and Jason Zhang in :gh:`115957`.)
741
742 * The function and methods named ``create_task`` have received a new
743 ``**kwargs`` argument that is passed through to the task constructor.
744 This change was accidentally added in 3.13.3,
745 and broke the API contract for custom task factories.
746 Several third-party task factories implemented workarounds for this.
747 In 3.13.4 and later releases the old factory contract is honored
748 once again (until 3.14).
749 To keep the workarounds working, the extra ``**kwargs`` argument still
750 allows passing additional keyword arguments to :class:`~asyncio.Task`
751 and to custom task factories.
752
753 This affects the following function and methods:
754 :meth:`asyncio.create_task`,
755 :meth:`asyncio.loop.create_task`,
756 :meth:`asyncio.TaskGroup.create_task`.
757 (Contributed by Thomas Grainger in :gh:`128307`.)
758
759 base64
760 ------
761
762 * Add :func:`~base64.z85encode` and :func:`~base64.z85decode` functions
763 for encoding :class:`bytes` as `Z85 data`_
764 and decoding Z85-encoded data to :class:`!bytes`.
765 (Contributed by Matan Perelman in :gh:`75299`.)
766
767 .. _Z85 data: https://rfc.zeromq.org/spec/32/
768
769
770 compileall
771 ----------
772
773 * The default number of worker threads and processes is now selected using
774 :func:`os.process_cpu_count` instead of :func:`os.cpu_count`.
775 (Contributed by Victor Stinner in :gh:`109649`.)
776
777
778 concurrent.futures
779 ------------------
780
781 * The default number of worker threads and processes is now selected using
782 :func:`os.process_cpu_count` instead of :func:`os.cpu_count`.
783 (Contributed by Victor Stinner in :gh:`109649`.)
784
785
786 configparser
787 ------------
788
789 * :class:`~configparser.ConfigParser` now has support for unnamed sections,
790 which allows for top-level key-value pairs.
791 This can be enabled with the new *allow_unnamed_section* parameter.
792 (Contributed by Pedro Sousa Lacerda in :gh:`66449`.)
793
794
795 copy
796 ----
797
798 * The new :func:`~copy.replace` function and the :meth:`replace protocol
799 <object.__replace__>` make creating modified copies of objects much simpler.
800 This is especially useful when working with immutable objects.
801 The following types support the :func:`~copy.replace` function
802 and implement the replace protocol:
803
804 * :func:`collections.namedtuple`
805 * :class:`dataclasses.dataclass`
806 * :class:`datetime.datetime`, :class:`datetime.date`, :class:`datetime.time`
807 * :class:`inspect.Signature`, :class:`inspect.Parameter`
808 * :class:`types.SimpleNamespace`
809 * :ref:`code objects <code-objects>`
810
811 Any user-defined class can also support :func:`copy.replace` by defining
812 the :meth:`~object.__replace__` method.
813 (Contributed by Serhiy Storchaka in :gh:`108751`.)
814
815
816 ctypes
817 ------
818
819 * As a consequence of necessary internal refactoring, initialization of
820 internal metaclasses now happens in ``__init__`` rather
821 than in ``__new__``. This affects projects that subclass these internal
822 metaclasses to provide custom initialization.
823 Generally:
824
825 - Custom logic that was done in ``__new__`` after calling ``super().__new__``
826 should be moved to ``__init__``.
827 - To create a class, call the metaclass, not only the metaclass's
828 ``__new__`` method.
829
830 See :gh:`124520` for discussion and links to changes in some affected
831 projects.
832
833 * :class:`ctypes.Structure` objects have a new :attr:`~ctypes.Structure._align_`
834 attribute which allows the alignment of the structure being packed to/from
835 memory to be specified explicitly.
836 (Contributed by Matt Sanderson in :gh:`112433`)
837
838 dbm
839 ---
840
841 * Add :mod:`dbm.sqlite3`, a new module which implements an SQLite backend,
842 and make it the default :mod:`!dbm` backend.
843 (Contributed by Raymond Hettinger and Erlend E. Aasland in :gh:`100414`.)
844
845 * Allow removing all items from the database through
846 the new :meth:`!clear` methods of the GDBM and NDBM database objects.
847 (Contributed by Donghee Na in :gh:`107122`.)
848
849
850 dis
851 ---
852
853 * Change the output of :mod:`dis` module functions to show logical
854 labels for jump targets and exception handlers, rather than offsets.
855 The offsets can be added with the new
856 :option:`-O <dis --show-offsets>` command-line option
857 or the *show_offsets* argument.
858 (Contributed by Irit Katriel in :gh:`112137`.)
859
860 * :meth:`~dis.get_instructions` no longer represents cache entries
861 as separate instructions.
862 Instead, it returns them as part of the :class:`~dis.Instruction`,
863 in the new *cache_info* field.
864 The *show_caches* argument to :meth:`~dis.get_instructions` is deprecated
865 and no longer has any effect.
866 (Contributed by Irit Katriel in :gh:`112962`.)
867
868
869 .. _whatsnew313-doctest:
870
871 doctest
872 -------
873
874 * :mod:`doctest` output is now colored by default.
875 This can be controlled via the new :envvar:`PYTHON_COLORS` environment
876 variable as well as the canonical |NO_COLOR|_
877 and |FORCE_COLOR|_ environment variables.
878 See also :ref:`using-on-controlling-color`.
879 (Contributed by Hugo van Kemenade in :gh:`117225`.)
880
881 * The :meth:`.DocTestRunner.run` method now counts the number of skipped tests.
882 Add the :attr:`.DocTestRunner.skips` and :attr:`.TestResults.skipped` attributes.
883 (Contributed by Victor Stinner in :gh:`108794`.)
884
885
886 email
887 -----
888
889 * Headers with embedded newlines are now quoted on output.
890 The :mod:`~email.generator` will now refuse to serialize (write) headers
891 that are improperly folded or delimited, such that they would be parsed as
892 multiple headers or joined with adjacent data.
893 If you need to turn this safety feature off,
894 set :attr:`~email.policy.Policy.verify_generated_headers`.
895 (Contributed by Bas Bloemsaat and Petr Viktorin in :gh:`121650`.)
896
897 * :func:`~email.utils.getaddresses` and :func:`~email.utils.parseaddr` now
898 return ``('', '')`` pairs in more situations where invalid email addresses
899 are encountered instead of potentially inaccurate values.
900 The two functions have a new optional *strict* parameter (default ``True``).
901 To get the old behavior (accepting malformed input), use ``strict=False``.
902 ``getattr(email.utils, 'supports_strict_parsing', False)`` can be used
903 to check if the *strict* parameter is available.
904 (Contributed by Thomas Dwyer and Victor Stinner for :gh:`102988` to improve
905 the :cve:`2023-27043` fix.)
906
907
908 enum
909 ----
910
911 * :class:`~enum.EnumDict` has been made public to better support subclassing
912 :class:`~enum.EnumType`.
913
914
915 fractions
916 ---------
917
918 * :class:`~fractions.Fraction` objects now support the standard
919 :ref:`format specification mini-language <formatspec>` rules
920 for fill, alignment, sign handling, minimum width, and grouping.
921 (Contributed by Mark Dickinson in :gh:`111320`.)
922
923
924 glob
925 ----
926
927 * Add :func:`~glob.translate`, a function to convert a path specification
928 with shell-style wildcards to a regular expression.
929 (Contributed by Barney Gale in :gh:`72904`.)
930
931
932 importlib
933 ---------
934
935 * The following functions in :mod:`importlib.resources` now allow accessing
936 a directory (or tree) of resources, using multiple positional arguments
937 (the *encoding* and *errors* arguments in the text-reading functions
938 are now keyword-only):
939
940 * :func:`~importlib.resources.is_resource`
941 * :func:`~importlib.resources.open_binary`
942 * :func:`~importlib.resources.open_text`
943 * :func:`~importlib.resources.path`
944 * :func:`~importlib.resources.read_binary`
945 * :func:`~importlib.resources.read_text`
946
947 These functions are no longer deprecated and are not scheduled for removal.
948 (Contributed by Petr Viktorin in :gh:`116608`.)
949
950 * :func:`~importlib.resources.contents` remains deprecated in favor of
951 the fully-featured :class:`~importlib.resources.abc.Traversable` API.
952 However, there is now no plan to remove it.
953 (Contributed by Petr Viktorin in :gh:`116608`.)
954
955
956 io
957 --
958
959 * The :class:`~io.IOBase` finalizer now logs any errors raised by
960 the :meth:`~io.IOBase.close` method with :data:`sys.unraisablehook`.
961 Previously, errors were ignored silently by default,
962 and only logged in :ref:`Python Development Mode <devmode>`
963 or when using a :ref:`Python debug build <debug-build>`.
964 (Contributed by Victor Stinner in :gh:`62948`.)
965
966
967 ipaddress
968 ---------
969
970 * Add the :attr:`.IPv4Address.ipv6_mapped` property,
971 which returns the IPv4-mapped IPv6 address.
972 (Contributed by Charles Machalow in :gh:`109466`.)
973
974 * Fix ``is_global`` and ``is_private`` behavior in
975 :class:`~ipaddress.IPv4Address`, :class:`~ipaddress.IPv6Address`,
976 :class:`~ipaddress.IPv4Network`, and :class:`~ipaddress.IPv6Network`.
977 (Contributed by Jakub Stasiak in :gh:`113171`.)
978
979
980 itertools
981 ---------
982
983 * :func:`~itertools.batched` has a new *strict* parameter,
984 which raises a :exc:`ValueError` if the final batch is shorter
985 than the specified batch size.
986 (Contributed by Raymond Hettinger in :gh:`113202`.)
987
988
989 marshal
990 -------
991
992 * Add the *allow_code* parameter in module functions.
993 Passing ``allow_code=False`` prevents serialization and de-serialization
994 of code objects which are incompatible between Python versions.
995 (Contributed by Serhiy Storchaka in :gh:`113626`.)
996
997
998 math
999 ----
1000
1001 * The new function :func:`~math.fma` performs fused multiply-add operations.
1002 This computes ``x * y + z`` with only a single round,
1003 and so avoids any intermediate loss of precision.
1004 It wraps the ``fma()`` function provided by C99,
1005 and follows the specification of the IEEE 754 "fusedMultiplyAdd" operation
1006 for special cases.
1007 (Contributed by Mark Dickinson and Victor Stinner in :gh:`73468`.)
1008
1009
1010 mimetypes
1011 ---------
1012
1013 * Add the :func:`~mimetypes.guess_file_type` function to guess a MIME type
1014 from a filesystem path.
1015 Using paths with :func:`~mimetypes.guess_type` is now :term:`soft deprecated`.
1016 (Contributed by Serhiy Storchaka in :gh:`66543`.)
1017
1018
1019 mmap
1020 ----
1021
1022 * :class:`~mmap.mmap` is now protected from crashing on Windows when the
1023 mapped memory is inaccessible due to file system errors or access violations.
1024 (Contributed by Jannis Weigend in :gh:`118209`.)
1025
1026 * :class:`~mmap.mmap` has a new :meth:`~mmap.mmap.seekable` method
1027 that can be used when a seekable file-like object is required.
1028 The :meth:`~mmap.mmap.seek` method now returns the new absolute position.
1029 (Contributed by Donghee Na and Sylvie Liberman in :gh:`111835`.)
1030
1031 * The new UNIX-only *trackfd* parameter for :class:`~mmap.mmap` controls
1032 file descriptor duplication;
1033 if false, the file descriptor specified by *fileno* will not be duplicated.
1034 (Contributed by Zackery Spytz and Petr Viktorin in :gh:`78502`.)
1035
1036
1037 multiprocessing
1038 ---------------
1039
1040 * The default number of worker threads and processes is now selected using
1041 :func:`os.process_cpu_count` instead of :func:`os.cpu_count`.
1042 (Contributed by Victor Stinner in :gh:`109649`.)
1043
1044
1045 os
1046 --
1047
1048 * Add :func:`~os.process_cpu_count` function to get the number
1049 of logical CPU cores usable by the calling thread of the current process.
1050 (Contributed by Victor Stinner in :gh:`109649`.)
1051
1052 * :func:`~os.cpu_count` and :func:`~os.process_cpu_count` can be overridden
1053 through the new environment variable :envvar:`PYTHON_CPU_COUNT`
1054 or the new command-line option :option:`-X cpu_count <-X>`.
1055 This option is useful for users who need to limit CPU resources
1056 of a container system without having to modify application code
1057 or the container itself.
1058 (Contributed by Donghee Na in :gh:`109595`.)
1059
1060 * Add a :ref:`low level interface <os-timerfd>` to Linux's
1061 :manpage:`timer file descriptors <timerfd_create(2)>`
1062 via :func:`~os.timerfd_create`,
1063 :func:`~os.timerfd_settime`, :func:`~os.timerfd_settime_ns`,
1064 :func:`~os.timerfd_gettime`, :func:`~os.timerfd_gettime_ns`,
1065 :const:`~os.TFD_NONBLOCK`, :const:`~os.TFD_CLOEXEC`,
1066 :const:`~os.TFD_TIMER_ABSTIME`, and :const:`~os.TFD_TIMER_CANCEL_ON_SET`
1067 (Contributed by Masaru Tsuchiyama in :gh:`108277`.)
1068
1069 * :func:`~os.lchmod` and the *follow_symlinks* argument of :func:`~os.chmod`
1070 are both now available on Windows.
1071 Note that the default value of *follow_symlinks*
1072 in :func:`!lchmod` is ``False`` on Windows.
1073 (Contributed by Serhiy Storchaka in :gh:`59616`.)
1074
1075 * :func:`~os.fchmod` and support for file descriptors in :func:`~os.chmod`
1076 are both now available on Windows.
1077 (Contributed by Serhiy Storchaka in :gh:`113191`.)
1078
1079 * On Windows, :func:`~os.mkdir` and :func:`~os.makedirs` now support passing
1080 a *mode* value of ``0o700`` to apply access control to the new directory.
1081 This implicitly affects :func:`tempfile.mkdtemp`
1082 and is a mitigation for :cve:`2024-4030`.
1083 Other values for *mode* continue to be ignored.
1084 (Contributed by Steve Dower in :gh:`118486`.)
1085
1086 * :func:`~os.posix_spawn` now accepts ``None`` for the *env* argument,
1087 which makes the newly spawned process use the current process environment.
1088 (Contributed by Jakub Kulik in :gh:`113119`.)
1089
1090 * :func:`~os.posix_spawn` can now use the :const:`~os.POSIX_SPAWN_CLOSEFROM`
1091 attribute in the *file_actions* parameter on platforms that support
1092 :c:func:`!posix_spawn_file_actions_addclosefrom_np`.
1093 (Contributed by Jakub Kulik in :gh:`113117`.)
1094
1095
1096 os.path
1097 -------
1098
1099 * Add :func:`~os.path.isreserved` to check if a path is reserved
1100 on the current system.
1101 This function is only available on Windows.
1102 (Contributed by Barney Gale in :gh:`88569`.)
1103
1104 * On Windows, :func:`~os.path.isabs` no longer considers paths
1105 starting with exactly one slash (``\`` or ``/``) to be absolute.
1106 (Contributed by Barney Gale and Jon Foster in :gh:`44626`.)
1107
1108 * :func:`~os.path.realpath` now resolves MS-DOS style file names
1109 even if the file is not accessible.
1110 (Contributed by Moonsik Park in :gh:`82367`.)
1111
1112
1113 pathlib
1114 -------
1115
1116 * Add :exc:`~pathlib.UnsupportedOperation`, which is raised instead of
1117 :exc:`NotImplementedError` when a path operation isn't supported.
1118 (Contributed by Barney Gale in :gh:`89812`.)
1119
1120 * Add a new constructor for creating :class:`~pathlib.Path` objects
1121 from 'file' URIs (``file:///``), :meth:`.Path.from_uri`.
1122 (Contributed by Barney Gale in :gh:`107465`.)
1123
1124 * Add :meth:`.PurePath.full_match` for matching paths with
1125 shell-style wildcards, including the recursive wildcard "``**``".
1126 (Contributed by Barney Gale in :gh:`73435`.)
1127
1128 * Add the :attr:`.PurePath.parser` class attribute to store the
1129 implementation of :mod:`os.path` used
1130 for low-level path parsing and joining.
1131 This will be either :mod:`!posixpath` or :mod:`!ntpath`.
1132
1133 * Add *recurse_symlinks* keyword-only argument to
1134 :meth:`.Path.glob` and :meth:`~pathlib.Path.rglob`.
1135 (Contributed by Barney Gale in :gh:`77609`.)
1136
1137 * :meth:`.Path.glob` and :meth:`~pathlib.Path.rglob`
1138 now return files and directories when given a pattern that ends with "``**``".
1139 Previously, only directories were returned.
1140 (Contributed by Barney Gale in :gh:`70303`.)
1141
1142 * Add the *follow_symlinks* keyword-only argument to
1143 :meth:`Path.is_file <pathlib.Path.is_file>`,
1144 :meth:`Path.is_dir <pathlib.Path.is_dir>`,
1145 :meth:`.Path.owner`, and :meth:`.Path.group`.
1146 (Contributed by Barney Gale in :gh:`105793` and Kamil Turek in :gh:`107962`.)
1147
1148
1149 pdb
1150 ---
1151
1152 * :func:`breakpoint` and :func:`~pdb.set_trace` now enter the debugger immediately
1153 rather than on the next line of code to be executed. This change prevents the
1154 debugger from breaking outside of the context when :func:`!breakpoint` is positioned
1155 at the end of the context.
1156 (Contributed by Tian Gao in :gh:`118579`.)
1157
1158 * ``sys.path[0]`` is no longer replaced by the directory of the script
1159 being debugged when :attr:`sys.flags.safe_path` is set.
1160 (Contributed by Tian Gao and Christian Walther in :gh:`111762`.)
1161
1162 * :mod:`zipapp` is now supported as a debugging target.
1163 (Contributed by Tian Gao in :gh:`118501`.)
1164
1165 * Add ability to move between chained exceptions during
1166 post-mortem debugging in :func:`~pdb.pm` using
1167 the new :pdbcmd:`exceptions [exc_number] <exceptions>` command for Pdb.
1168 (Contributed by Matthias Bussonnier in :gh:`106676`.)
1169
1170 * Expressions and statements whose prefix is a pdb command are now correctly
1171 identified and executed.
1172 (Contributed by Tian Gao in :gh:`108464`.)
1173
1174
1175 queue
1176 -----
1177
1178 * Add :meth:`Queue.shutdown <queue.Queue.shutdown>` and :exc:`~queue.ShutDown`
1179 to manage queue termination.
1180 (Contributed by Laurie Opperman and Yves Duprat in :gh:`104750`.)
1181
1182
1183 random
1184 ------
1185
1186 * Add a :ref:`command-line interface <random-cli>`.
1187 (Contributed by Hugo van Kemenade in :gh:`118131`.)
1188
1189
1190 re
1191 --
1192
1193 * Rename :exc:`!re.error` to :exc:`~re.PatternError` for improved clarity.
1194 :exc:`!re.error` is kept for backward compatibility.
1195
1196
1197 shutil
1198 ------
1199
1200 * Support the *dir_fd* and *follow_symlinks* keyword arguments
1201 in :func:`~shutil.chown`.
1202 (Contributed by Berker Peksag and Tahia K in :gh:`62308`)
1203
1204
1205 site
1206 ----
1207
1208 * :file:`.pth` files are now decoded using UTF-8 first,
1209 and then with the :term:`locale encoding` if UTF-8 decoding fails.
1210 (Contributed by Inada Naoki in :gh:`117802`.)
1211
1212
1213 sqlite3
1214 -------
1215
1216 * A :exc:`ResourceWarning` is now emitted if a :class:`~sqlite3.Connection`
1217 object is not :meth:`closed <sqlite3.Connection.close>` explicitly.
1218 (Contributed by Erlend E. Aasland in :gh:`105539`.)
1219
1220 * Add the *filter* keyword-only parameter to :meth:`.Connection.iterdump`
1221 for filtering database objects to dump.
1222 (Contributed by Mariusz Felisiak in :gh:`91602`.)
1223
1224
1225 ssl
1226 ---
1227
1228 * The :func:`~ssl.create_default_context` API now includes
1229 :data:`~ssl.VERIFY_X509_PARTIAL_CHAIN` and :data:`~ssl.VERIFY_X509_STRICT`
1230 in its default flags.
1231
1232 .. note::
1233
1234 :data:`~ssl.VERIFY_X509_STRICT` may reject pre-:rfc:`5280`
1235 or malformed certificates that the underlying OpenSSL implementation
1236 might otherwise accept.
1237 Whilst disabling this is not recommended, you can do so using:
1238
1239 .. code-block:: python
1240
1241 import ssl
1242
1243 ctx = ssl.create_default_context()
1244 ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
1245
1246 (Contributed by William Woodruff in :gh:`112389`.)
1247
1248
1249 statistics
1250 ----------
1251
1252 * Add :func:`~statistics.kde` for kernel density estimation.
1253 This makes it possible to estimate a continuous probability density function
1254 from a fixed number of discrete samples.
1255 (Contributed by Raymond Hettinger in :gh:`115863`.)
1256
1257 * Add :func:`~statistics.kde_random` for sampling from an
1258 estimated probability density function created by :func:`~statistics.kde`.
1259 (Contributed by Raymond Hettinger in :gh:`115863`.)
1260
1261
1262 .. _whatsnew313-subprocess:
1263
1264 subprocess
1265 ----------
1266
1267 * The :mod:`subprocess` module now uses the :func:`~os.posix_spawn` function in
1268 more situations.
1269
1270 Notably, when *close_fds* is ``True`` (the default),
1271 :func:`~os.posix_spawn` will be used when the C library provides
1272 :c:func:`!posix_spawn_file_actions_addclosefrom_np`,
1273 which includes recent versions of Linux, FreeBSD, and Solaris.
1274 On Linux, this should perform similarly to the existing
1275 Linux :c:func:`!vfork` based code.
1276
1277 A private control knob :attr:`!subprocess._USE_POSIX_SPAWN` can
1278 be set to ``False`` if you need to force :mod:`subprocess`
1279 to never use :func:`~os.posix_spawn`.
1280 Please report your reason and platform details in
1281 the :ref:`issue tracker <using-the-tracker>` if you set this
1282 so that we can improve our API selection logic for everyone.
1283 (Contributed by Jakub Kulik in :gh:`113117`.)
1284
1285
1286 sys
1287 ---
1288
1289 * Add the :func:`~sys._is_interned` function to test if a string was interned.
1290 This function is not guaranteed to exist in all implementations of Python.
1291 (Contributed by Serhiy Storchaka in :gh:`78573`.)
1292
1293
1294 tempfile
1295 --------
1296
1297 * On Windows, the default mode ``0o700`` used by :func:`tempfile.mkdtemp` now
1298 limits access to the new directory due to changes to :func:`os.mkdir`.
1299 This is a mitigation for :cve:`2024-4030`.
1300 (Contributed by Steve Dower in :gh:`118486`.)
1301
1302
1303 time
1304 ----
1305
1306 * On Windows, :func:`~time.monotonic` now uses the
1307 ``QueryPerformanceCounter()`` clock for a resolution of 1 microsecond,
1308 instead of the ``GetTickCount64()`` clock which has
1309 a resolution of 15.6 milliseconds.
1310 (Contributed by Victor Stinner in :gh:`88494`.)
1311
1312 * On Windows, :func:`~time.time` now uses the
1313 ``GetSystemTimePreciseAsFileTime()`` clock for a resolution of 1 microsecond,
1314 instead of the ``GetSystemTimeAsFileTime()`` clock which has
1315 a resolution of 15.6 milliseconds.
1316 (Contributed by Victor Stinner in :gh:`63207`.)
1317
1318
1319 tkinter
1320 -------
1321
1322 * Add :mod:`tkinter` widget methods:
1323 :meth:`!tk_busy_hold`, :meth:`!tk_busy_configure`,
1324 :meth:`!tk_busy_cget`, :meth:`!tk_busy_forget`,
1325 :meth:`!tk_busy_current`, and :meth:`!tk_busy_status`.
1326 (Contributed by Miguel, klappnase and Serhiy Storchaka in :gh:`72684`.)
1327
1328 * The :mod:`tkinter` widget method :meth:`!wm_attributes` now accepts
1329 the attribute name without the minus prefix to get window attributes,
1330 for example ``w.wm_attributes('alpha')``
1331 and allows specifying attributes and values to set as keyword arguments,
1332 for example ``w.wm_attributes(alpha=0.5)``.
1333 (Contributed by Serhiy Storchaka in :gh:`43457`.)
1334
1335 * :meth:`!wm_attributes` can now return attributes as a :class:`dict`,
1336 by using the new optional keyword-only parameter *return_python_dict*.
1337 (Contributed by Serhiy Storchaka in :gh:`43457`.)
1338
1339 * :meth:`!Text.count` can now return a simple :class:`int`
1340 when the new optional keyword-only parameter *return_ints* is used.
1341 Otherwise, the single count is returned as a 1-tuple or ``None``.
1342 (Contributed by Serhiy Storchaka in :gh:`97928`.)
1343
1344 * Support the "vsapi" element type in
1345 the :meth:`~tkinter.ttk.Style.element_create` method of
1346 :class:`tkinter.ttk.Style`.
1347 (Contributed by Serhiy Storchaka in :gh:`68166`.)
1348
1349 * Add the :meth:`!after_info` method for Tkinter widgets.
1350 (Contributed by Cheryl Sabella in :gh:`77020`.)
1351
1352 * Add a new :meth:`!copy_replace` method to :class:`!PhotoImage`
1353 to copy a region from one image to another,
1354 possibly with pixel zooming, subsampling, or both.
1355 (Contributed by Serhiy Storchaka in :gh:`118225`.)
1356
1357 * Add *from_coords* parameter to the :class:`!PhotoImage` methods
1358 :meth:`!copy`, :meth:`!zoom` and :meth:`!subsample`.
1359 Add *zoom* and *subsample* parameters to the :class:`!PhotoImage` method
1360 :meth:`!copy`.
1361 (Contributed by Serhiy Storchaka in :gh:`118225`.)
1362
1363 * Add the :class:`!PhotoImage` methods
1364 :meth:`!read` to read an image from a file
1365 and :meth:`!data` to get the image data.
1366 Add *background* and *grayscale* parameters to the :meth:`!write` method.
1367 (Contributed by Serhiy Storchaka in :gh:`118271`.)
1368
1369
1370 traceback
1371 ---------
1372
1373 * Add the :attr:`~traceback.TracebackException.exc_type_str` attribute
1374 to :class:`~traceback.TracebackException`,
1375 which holds a string display of the *exc_type*.
1376 Deprecate the :attr:`~traceback.TracebackException.exc_type` attribute,
1377 which holds the type object itself.
1378 Add parameter *save_exc_type* (default ``True``)
1379 to indicate whether ``exc_type`` should be saved.
1380 (Contributed by Irit Katriel in :gh:`112332`.)
1381
1382 * Add a new *show_group* keyword-only parameter to
1383 :meth:`.TracebackException.format_exception_only` to (recursively) format
1384 the nested exceptions of a :exc:`BaseExceptionGroup` instance.
1385 (Contributed by Irit Katriel in :gh:`105292`.)
1386
1387
1388 types
1389 -----
1390
1391 * :class:`~types.SimpleNamespace` can now take a single positional argument
1392 to initialise the namespace's arguments.
1393 This argument must either be a mapping or an iterable of key-value pairs.
1394 (Contributed by Serhiy Storchaka in :gh:`108191`.)
1395
1396
1397 typing
1398 ------
1399
1400 * :pep:`705`: Add :data:`~typing.ReadOnly`, a special typing construct
1401 to mark a :class:`~typing.TypedDict` item as read-only for type checkers.
1402
1403 * :pep:`742`: Add :data:`~typing.TypeIs`, a typing construct
1404 that can be used to instruct a type checker how to narrow a type.
1405
1406 * Add :data:`~typing.NoDefault`, a sentinel object used to represent
1407 the defaults of some parameters in the :mod:`typing` module.
1408 (Contributed by Jelle Zijlstra in :gh:`116126`.)
1409
1410 * Add :func:`~typing.get_protocol_members` to return the set of members
1411 defining a :class:`typing.Protocol`.
1412 (Contributed by Jelle Zijlstra in :gh:`104873`.)
1413
1414 * Add :func:`~typing.is_protocol` to check whether a class
1415 is a :class:`~typing.Protocol`.
1416 (Contributed by Jelle Zijlstra in :gh:`104873`.)
1417
1418 * :data:`~typing.ClassVar` can now be nested in :data:`~typing.Final`,
1419 and vice versa.
1420 (Contributed by Mehdi Drissi in :gh:`89547`.)
1421
1422
1423 unicodedata
1424 -----------
1425
1426 * Update the Unicode database to `version 15.1.0`__.
1427 (Contributed by James Gerity in :gh:`109559`.)
1428
1429 __ https://www.unicode.org/versions/Unicode15.1.0/
1430
1431
1432 venv
1433 ----
1434
1435 * Add support for creating source control management (SCM) ignore files
1436 in a virtual environment's directory.
1437 By default, Git is supported.
1438 This is implemented as opt-in via the API,
1439 which can be extended to support other SCMs
1440 (:class:`~venv.EnvBuilder` and :func:`~venv.create`),
1441 and opt-out via the CLI, using :option:`!--without-scm-ignore-files`.
1442 (Contributed by Brett Cannon in :gh:`108125`.)
1443
1444
1445 warnings
1446 --------
1447
1448 * :pep:`702`: The new :func:`warnings.deprecated` decorator provides a way to
1449 communicate deprecations to a :term:`static type checker`
1450 and to warn on usage of deprecated classes and functions.
1451 A :exc:`DeprecationWarning` may also be emitted when
1452 a decorated function or class is used at runtime.
1453 (Contributed by Jelle Zijlstra in :gh:`104003`.)
1454
1455
1456 xml
1457 ---
1458
1459 * Allow controlling Expat >=2.6.0 reparse deferral (:cve:`2023-52425`)
1460 by adding five new methods:
1461
1462 * :meth:`xml.etree.ElementTree.XMLParser.flush`
1463 * :meth:`xml.etree.ElementTree.XMLPullParser.flush`
1464 * :meth:`xml.parsers.expat.xmlparser.GetReparseDeferralEnabled`
1465 * :meth:`xml.parsers.expat.xmlparser.SetReparseDeferralEnabled`
1466 * :meth:`!xml.sax.expatreader.ExpatParser.flush`
1467
1468 (Contributed by Sebastian Pipping in :gh:`115623`.)
1469
1470 * Add the :meth:`!close` method for the iterator returned by
1471 :func:`~xml.etree.ElementTree.iterparse` for explicit cleanup.
1472 (Contributed by Serhiy Storchaka in :gh:`69893`.)
1473
1474
1475 zipimport
1476 ---------
1477
1478 * Add support for ZIP64_ format files.
1479 Everybody loves huge data, right?
1480 (Contributed by Tim Hatch in :gh:`94146`.)
1481
1482 .. _ZIP64: https://en.wikipedia.org/wiki/Zip_(file_format)#ZIP64
1483
1484
1485 Optimizations
1486 =============
1487
1488 * Several standard library modules have had
1489 their import times significantly improved.
1490 For example, the import time of the :mod:`typing` module
1491 has been reduced by around a third by removing dependencies
1492 on :mod:`re` and :mod:`contextlib`.
1493 Other modules to enjoy import-time speedups include
1494 :mod:`email.utils`, :mod:`enum`, :mod:`functools`,
1495 :mod:`importlib.metadata`, and :mod:`threading`.
1496 (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas,
1497 and others in :gh:`109653`.)
1498
1499 * :func:`textwrap.indent` is now around 30% faster than before for large input.
1500 (Contributed by Inada Naoki in :gh:`107369`.)
1501
1502 * The :mod:`subprocess` module now uses the :func:`~os.posix_spawn` function in
1503 more situations, including when *close_fds* is ``True`` (the default)
1504 on many modern platforms.
1505 This should provide a notable performance increase
1506 when launching processes on FreeBSD and Solaris.
1507 See the :ref:`subprocess <whatsnew313-subprocess>` section above for details.
1508 (Contributed by Jakub Kulik in :gh:`113117`.)
1509
1510
1511 Removed Modules And APIs
1512 ========================
1513
1514
1515 .. _whatsnew313-pep594:
1516
1517 PEP 594: Remove "dead batteries" from the standard library
1518 ----------------------------------------------------------
1519
1520 :pep:`594` proposed removing 19 modules from the standard library,
1521 colloquially referred to as 'dead batteries' due to their
1522 historic, obsolete, or insecure status.
1523 All of the following modules were deprecated in Python 3.11,
1524 and are now removed:
1525
1526 * :mod:`!aifc`
1527
1528 * :pypi:`standard-aifc`:
1529 Use the redistribution of ``aifc`` library from PyPI.
1530
1531 * :mod:`!audioop`
1532
1533 * :pypi:`audioop-lts`:
1534 Use ``audioop-lts`` library from PyPI.
1535
1536 * :mod:`!chunk`
1537
1538 * :pypi:`standard-chunk`:
1539 Use the redistribution of ``chunk`` library from PyPI.
1540
1541 * :mod:`!cgi` and :mod:`!cgitb`
1542
1543 * :class:`!cgi.FieldStorage` can typically be replaced with
1544 :func:`urllib.parse.parse_qsl` for ``GET`` and ``HEAD`` requests,
1545 and the :mod:`email.message` module or the :pypi:`multipart` library
1546 for ``POST`` and ``PUT`` requests.
1547
1548 * :func:`!cgi.parse` can be replaced by calling
1549 :func:`urllib.parse.parse_qs` directly on the desired query string,
1550 unless the input is ``multipart/form-data``,
1551 which should be replaced as described below for :func:`!cgi.parse_multipart`.
1552
1553 * :func:`!cgi.parse_header` can be replaced with the functionality
1554 in the :mod:`email` package, which implements the same MIME RFCs.
1555 For example, with :class:`email.message.EmailMessage`:
1556
1557 .. code-block:: python
1558
1559 from email.message import EmailMessage
1560
1561 msg = EmailMessage()
1562 msg['content-type'] = 'application/json; charset="utf8"'
1563 main, params = msg.get_content_type(), msg['content-type'].params
1564
1565 * :func:`!cgi.parse_multipart` can be replaced with the functionality
1566 in the :mod:`email` package, which implements the same MIME RFCs,
1567 or with the :pypi:`multipart` library.
1568 For example, the :class:`email.message.EmailMessage`
1569 and :class:`email.message.Message` classes.
1570
1571 * :pypi:`standard-cgi`: and :pypi:`standard-cgitb`:
1572 Use the redistribution of ``cgi`` and ``cgitb`` library from PyPI.
1573
1574 * :mod:`!crypt` and the private :mod:`!_crypt` extension.
1575 The :mod:`hashlib` module may be an appropriate replacement
1576 when simply hashing a value is required.
1577 Otherwise, various third-party libraries on PyPI are available:
1578
1579 * :pypi:`bcrypt`:
1580 Modern password hashing for your software and your servers.
1581 * :pypi:`argon2-cffi`:
1582 The secure Argon2 password hashing algorithm.
1583 * :pypi:`legacycrypt`:
1584 :mod:`ctypes` wrapper to the POSIX crypt library call
1585 and associated functionality.
1586 * :pypi:`crypt_r`:
1587 Fork of the :mod:`!crypt` module,
1588 wrapper to the :manpage:`crypt_r(3)` library call
1589 and associated functionality.
1590 * :pypi:`standard-crypt` and :pypi:`deprecated-crypt-alternative`:
1591 Use the redistribution of ``crypt`` and reimplementation of ``_crypt`` libraries from PyPI.
1592
1593 * :mod:`!imghdr`:
1594 The :pypi:`filetype`, :pypi:`puremagic`, or :pypi:`python-magic` libraries
1595 should be used as replacements.
1596 For example, the :func:`!puremagic.what` function can be used
1597 to replace the :func:`!imghdr.what` function for all file formats
1598 that were supported by :mod:`!imghdr`.
1599
1600 * :pypi:`standard-imghdr`:
1601 Use the redistribution of ``imghdr`` library from PyPI.
1602
1603 * :mod:`!mailcap`:
1604 Use the :mod:`mimetypes` module instead.
1605
1606 * :pypi:`standard-mailcap`:
1607 Use the redistribution of ``mailcap`` library from PyPI.
1608
1609 * :mod:`!msilib`
1610 * :mod:`!nis`
1611 * :mod:`!nntplib`:
1612 Use the :pypi:`pynntp` library from PyPI instead.
1613
1614 * :pypi:`standard-nntplib`:
1615 Use the redistribution of ``nntplib`` library from PyPI.
1616
1617 * :mod:`!ossaudiodev`:
1618 For audio playback, use the :pypi:`pygame` library from PyPI instead.
1619 * :mod:`!pipes`:
1620 Use the :mod:`subprocess` module instead.
1621 Use :func:`shlex.quote` to replace the undocumented ``pipes.quote``
1622 function.
1623
1624 * :pypi:`standard-pipes`:
1625 Use the redistribution of ``pipes`` library from PyPI.
1626
1627 * :mod:`!sndhdr`:
1628 The :pypi:`filetype`, :pypi:`puremagic`, or :pypi:`python-magic` libraries
1629 should be used as replacements.
1630
1631 * :pypi:`standard-sndhdr`:
1632 Use the redistribution of ``sndhdr`` library from PyPI.
1633
1634 * :mod:`!spwd`:
1635 Use the :pypi:`python-pam` library from PyPI instead.
1636 * :mod:`!sunau`
1637
1638 * :pypi:`standard-sunau`:
1639 Use the redistribution of ``sunau`` library from PyPI.
1640
1641 * :mod:`!telnetlib`,
1642 Use the :pypi:`telnetlib3` or :pypi:`Exscript` libraries from PyPI instead.
1643
1644 * :pypi:`standard-telnetlib`:
1645 Use the redistribution of ``telnetlib`` library from PyPI.
1646
1647 * :mod:`!uu`:
1648 Use the :mod:`base64` module instead, as a modern alternative.
1649
1650 * :pypi:`standard-uu`:
1651 Use the redistribution of ``uu`` library from PyPI.
1652
1653 * :mod:`!xdrlib`
1654
1655 * :pypi:`standard-xdrlib`:
1656 Use the redistribution of ``xdrlib`` library from PyPI.
1657
1658 (Contributed by Victor Stinner and Zachary Ware in :gh:`104773` and :gh:`104780`.)
1659
1660
1661 2to3
1662 ----
1663
1664 * Remove the :program:`2to3` program and the :mod:`!lib2to3` module,
1665 previously deprecated in Python 3.11.
1666 (Contributed by Victor Stinner in :gh:`104780`.)
1667
1668
1669 builtins
1670 --------
1671
1672 * Remove support for chained :class:`classmethod` descriptors
1673 (introduced in :gh:`63272`).
1674 These can no longer be used to wrap other descriptors,
1675 such as :class:`property`.
1676 The core design of this feature was flawed and led to several problems.
1677 To "pass-through" a :class:`classmethod`, consider using
1678 the :attr:`!__wrapped__` attribute that was added in Python 3.10.
1679 (Contributed by Raymond Hettinger in :gh:`89519`.)
1680
1681 * Raise a :exc:`RuntimeError` when calling :meth:`frame.clear`
1682 on a suspended frame (as has always been the case for an executing frame).
1683 (Contributed by Irit Katriel in :gh:`79932`.)
1684
1685
1686 configparser
1687 ------------
1688
1689 * Remove the undocumented :class:`!LegacyInterpolation` class,
1690 deprecated in the docstring since Python 3.2,
1691 and at runtime since Python 3.11.
1692 (Contributed by Hugo van Kemenade in :gh:`104886`.)
1693
1694
1695 importlib.metadata
1696 ------------------
1697
1698 * Remove deprecated subscript (:meth:`~object.__getitem__`) access for
1699 :ref:`EntryPoint <entry-points>` objects.
1700 (Contributed by Jason R. Coombs in :gh:`113175`.)
1701
1702
1703 locale
1704 ------
1705
1706 * Remove the :func:`!locale.resetlocale` function, deprecated in Python 3.11.
1707 Use ``locale.setlocale(locale.LC_ALL, "")`` instead.
1708 (Contributed by Victor Stinner in :gh:`104783`.)
1709
1710
1711 opcode
1712 ------
1713
1714 * Move :attr:`!opcode.ENABLE_SPECIALIZATION` to :attr:`!_opcode.ENABLE_SPECIALIZATION`.
1715 This field was added in 3.12, it was never documented,
1716 and is not intended for external use.
1717 (Contributed by Irit Katriel in :gh:`105481`.)
1718
1719 * Remove :func:`!opcode.is_pseudo`, :attr:`!opcode.MIN_PSEUDO_OPCODE`,
1720 and :attr:`!opcode.MAX_PSEUDO_OPCODE`, which were added in Python 3.12,
1721 but were neither documented nor exposed through :mod:`dis`,
1722 and were not intended to be used externally.
1723 (Contributed by Irit Katriel in :gh:`105481`.)
1724
1725
1726 optparse
1727 --------
1728
1729 * This module is no longer considered :term:`soft deprecated`.
1730 While :mod:`argparse` remains preferred for new projects that
1731 aren't using a third party command line argument processing
1732 library, there are aspects of the way ``argparse`` works that
1733 mean the lower level ``optparse`` module may provide a better
1734 foundation for *writing* argument processing libraries, and
1735 for implementing command line applications which adhere more
1736 strictly than ``argparse`` does to various Unix command line
1737 processing conventions that originate in the behaviour of the
1738 C :c:func:`!getopt` function .
1739 (Contributed by Alyssa Coghlan and Serhiy Storchaka in :gh:`126180`.)
1740
1741
1742 pathlib
1743 -------
1744
1745 * Remove the ability to use :class:`~pathlib.Path` objects as context managers.
1746 This functionality was deprecated and has had no effect since Python 3.9.
1747 (Contributed by Barney Gale in :gh:`83863`.)
1748
1749
1750 re
1751 --
1752
1753 * Remove the undocumented, deprecated, and broken
1754 :func:`!re.template` function and :attr:`!re.TEMPLATE` / :attr:`!re.T` flag.
1755 (Contributed by Serhiy Storchaka and Nikita Sobolev in :gh:`105687`.)
1756
1757
1758 tkinter.tix
1759 -----------
1760
1761 * Remove the :mod:`!tkinter.tix` module, deprecated in Python 3.6.
1762 The third-party Tix library which the module wrapped is unmaintained.
1763 (Contributed by Zachary Ware in :gh:`75552`.)
1764
1765
1766 turtle
1767 ------
1768
1769 * Remove the :meth:`!RawTurtle.settiltangle` method,
1770 deprecated in the documentation since Python 3.1
1771 and at runtime since Python 3.11.
1772 (Contributed by Hugo van Kemenade in :gh:`104876`.)
1773
1774
1775 typing
1776 ------
1777
1778 * Remove the :mod:`!typing.io` and :mod:`!typing.re` namespaces,
1779 deprecated since Python 3.8.
1780 The items in those namespaces can be imported directly
1781 from the :mod:`typing` module.
1782 (Contributed by Sebastian Rittau in :gh:`92871`.)
1783
1784 * Remove the keyword-argument method of creating
1785 :class:`~typing.TypedDict` types, deprecated in Python 3.11.
1786 (Contributed by Tomas Roun in :gh:`104786`.)
1787
1788
1789 unittest
1790 --------
1791
1792 * Remove the following :mod:`unittest` functions, deprecated in Python 3.11:
1793
1794 * :func:`!unittest.findTestCases`
1795 * :func:`!unittest.makeSuite`
1796 * :func:`!unittest.getTestCaseNames`
1797
1798 Use :class:`~unittest.TestLoader` methods instead:
1799
1800 * :meth:`~unittest.TestLoader.loadTestsFromModule`
1801 * :meth:`~unittest.TestLoader.loadTestsFromTestCase`
1802 * :meth:`~unittest.TestLoader.getTestCaseNames`
1803
1804 (Contributed by Hugo van Kemenade in :gh:`104835`.)
1805
1806 * Remove the untested and undocumented :meth:`!TestProgram.usageExit`
1807 method, deprecated in Python 3.11.
1808 (Contributed by Hugo van Kemenade in :gh:`104992`.)
1809
1810
1811 urllib
1812 ------
1813
1814 * Remove the *cafile*, *capath*, and *cadefault* parameters of the
1815 :func:`urllib.request.urlopen` function, deprecated in Python 3.6.
1816 Use the *context* parameter instead with an :class:`~ssl.SSLContext` instance.
1817 The :meth:`ssl.SSLContext.load_cert_chain` function
1818 can be used to load specific certificates,
1819 or let :func:`ssl.create_default_context` select
1820 the operating system's trusted certificate authority (CA) certificates.
1821 (Contributed by Victor Stinner in :gh:`105382`.)
1822
1823
1824 webbrowser
1825 ----------
1826
1827 * Remove the untested and undocumented :class:`!MacOSX` class,
1828 deprecated in Python 3.11.
1829 Use the :class:`!MacOSXOSAScript` class (introduced in Python 3.2) instead.
1830 (Contributed by Hugo van Kemenade in :gh:`104804`.)
1831
1832 * Remove the deprecated :attr:`!MacOSXOSAScript._name` attribute.
1833 Use the :attr:`MacOSXOSAScript.name <webbrowser.controller.name>`
1834 attribute instead.
1835 (Contributed by Nikita Sobolev in :gh:`105546`.)
1836
1837
1838 New Deprecations
1839 ================
1840
1841 * :ref:`User-defined functions <user-defined-funcs>`:
1842
1843 * Deprecate assignment to a function's :attr:`~function.__code__` attribute,
1844 where the new code object's type does not match the function's type.
1845 The different types are:
1846 plain function, generator, async generator, and coroutine.
1847 (Contributed by Irit Katriel in :gh:`81137`.)
1848
1849 * :mod:`array`:
1850
1851 * Deprecate the ``'u'`` format code (:c:type:`wchar_t`) at runtime.
1852 This format code has been deprecated in documentation since Python 3.3,
1853 and will be removed in Python 3.16.
1854 Use the ``'w'`` format code (:c:type:`Py_UCS4`)
1855 for Unicode characters instead.
1856 (Contributed by Hugo van Kemenade in :gh:`80480`.)
1857
1858 * :mod:`ctypes`:
1859
1860 * Deprecate the undocumented :func:`!SetPointerType` function,
1861 to be removed in Python 3.15.
1862 (Contributed by Victor Stinner in :gh:`105733`.)
1863
1864 * :term:`Soft-deprecate <soft deprecated>` the :func:`~ctypes.ARRAY`
1865 function in favour of ``type * length`` multiplication.
1866 (Contributed by Victor Stinner in :gh:`105733`.)
1867
1868 * :mod:`decimal`:
1869
1870 * Deprecate the non-standard and undocumented :class:`~decimal.Decimal`
1871 format specifier ``'N'``,
1872 which is only supported in the :mod:`!decimal` module's C implementation.
1873 Scheduled to be removed in Python 3.18.
1874 (Contributed by Serhiy Storchaka in :gh:`89902`.)
1875
1876 * :mod:`dis`:
1877
1878 * Deprecate the :attr:`!HAVE_ARGUMENT` separator.
1879 Check membership in :data:`~dis.hasarg` instead.
1880 (Contributed by Irit Katriel in :gh:`109319`.)
1881
1882 * :mod:`gettext`:
1883
1884 * Deprecate non-integer numbers as arguments to functions and methods
1885 that consider plural forms in the :mod:`!gettext` module,
1886 even if no translation was found.
1887 (Contributed by Serhiy Storchaka in :gh:`88434`.)
1888
1889 * :mod:`glob`:
1890
1891 * Deprecate the undocumented :func:`!glob0` and :func:`!glob1` functions.
1892 Use :func:`~glob.glob` and pass a :term:`path-like object` specifying
1893 the root directory to the *root_dir* parameter instead.
1894 (Contributed by Barney Gale in :gh:`117337`.)
1895
1896 * :mod:`http.server`:
1897
1898 * Deprecate :class:`~http.server.CGIHTTPRequestHandler`,
1899 to be removed in Python 3.15.
1900 Process-based CGI HTTP servers have been out of favor for a very long time.
1901 This code was outdated, unmaintained, and rarely used.
1902 It has a high potential for both security and functionality bugs.
1903 (Contributed by Gregory P. Smith in :gh:`109096`.)
1904
1905 * Deprecate the :option:`!--cgi` flag to
1906 the :program:`python -m http.server` command-line interface,
1907 to be removed in Python 3.15.
1908 (Contributed by Gregory P. Smith in :gh:`109096`.)
1909
1910 * :mod:`mimetypes`:
1911
1912 * :term:`Soft-deprecate <soft deprecated>` file path arguments
1913 to :func:`~mimetypes.guess_type`,
1914 use :func:`~mimetypes.guess_file_type` instead.
1915 (Contributed by Serhiy Storchaka in :gh:`66543`.)
1916
1917 * :mod:`re`:
1918
1919 * Deprecate passing the optional *maxsplit*, *count*, or *flags* arguments
1920 as positional arguments to the module-level
1921 :func:`~re.split`, :func:`~re.sub`, and :func:`~re.subn` functions.
1922 These parameters will become :ref:`keyword-only <keyword-only_parameter>`
1923 in a future version of Python.
1924 (Contributed by Serhiy Storchaka in :gh:`56166`.)
1925
1926 * :mod:`pathlib`:
1927
1928 * Deprecate :meth:`.PurePath.is_reserved`,
1929 to be removed in Python 3.15.
1930 Use :func:`os.path.isreserved` to detect reserved paths on Windows.
1931 (Contributed by Barney Gale in :gh:`88569`.)
1932
1933 * :mod:`platform`:
1934
1935 * Deprecate :func:`~platform.java_ver`,
1936 to be removed in Python 3.15.
1937 This function is only useful for Jython support, has a confusing API,
1938 and is largely untested.
1939 (Contributed by Nikita Sobolev in :gh:`116349`.)
1940
1941 * :mod:`pydoc`:
1942
1943 * Deprecate the undocumented :func:`!ispackage` function.
1944 (Contributed by Zackery Spytz in :gh:`64020`.)
1945
1946 * :mod:`sqlite3`:
1947
1948 * Deprecate passing more than one positional argument to
1949 the :func:`~sqlite3.connect` function
1950 and the :class:`~sqlite3.Connection` constructor.
1951 The remaining parameters will become keyword-only in Python 3.15.
1952 (Contributed by Erlend E. Aasland in :gh:`107948`.)
1953
1954 * Deprecate passing name, number of arguments, and the callable as keyword
1955 arguments for :meth:`.Connection.create_function`
1956 and :meth:`.Connection.create_aggregate`
1957 These parameters will become positional-only in Python 3.15.
1958 (Contributed by Erlend E. Aasland in :gh:`108278`.)
1959
1960 * Deprecate passing the callback callable by keyword for the
1961 :meth:`~sqlite3.Connection.set_authorizer`,
1962 :meth:`~sqlite3.Connection.set_progress_handler`, and
1963 :meth:`~sqlite3.Connection.set_trace_callback`
1964 :class:`~sqlite3.Connection` methods.
1965 The callback callables will become positional-only in Python 3.15.
1966 (Contributed by Erlend E. Aasland in :gh:`108278`.)
1967
1968 * :mod:`sys`:
1969
1970 * Deprecate the :func:`~sys._enablelegacywindowsfsencoding` function,
1971 to be removed in Python 3.16.
1972 Use the :envvar:`PYTHONLEGACYWINDOWSFSENCODING` environment variable instead.
1973 (Contributed by Inada Naoki in :gh:`73427`.)
1974
1975 * :mod:`tarfile`:
1976
1977 * Deprecate the undocumented and unused :attr:`!TarFile.tarfile` attribute,
1978 to be removed in Python 3.16.
1979 (Contributed in :gh:`115256`.)
1980
1981 * :mod:`traceback`:
1982
1983 * Deprecate the :attr:`.TracebackException.exc_type` attribute.
1984 Use :attr:`.TracebackException.exc_type_str` instead.
1985 (Contributed by Irit Katriel in :gh:`112332`.)
1986
1987 * :mod:`typing`:
1988
1989 * Deprecate the undocumented keyword argument syntax for creating
1990 :class:`~typing.NamedTuple` classes
1991 (e.g. ``Point = NamedTuple("Point", x=int, y=int)``),
1992 to be removed in Python 3.15.
1993 Use the class-based syntax or the functional syntax instead.
1994 (Contributed by Alex Waygood in :gh:`105566`.)
1995
1996 * Deprecate omitting the *fields* parameter when creating
1997 a :class:`~typing.NamedTuple` or :class:`typing.TypedDict` class,
1998 and deprecate passing ``None`` to the *fields* parameter of both types.
1999 Python 3.15 will require a valid sequence for the *fields* parameter.
2000 To create a NamedTuple class with zero fields,
2001 use ``class NT(NamedTuple): pass`` or ``NT = NamedTuple("NT", ())``.
2002 To create a TypedDict class with zero fields,
2003 use ``class TD(TypedDict): pass`` or ``TD = TypedDict("TD", {})``.
2004 (Contributed by Alex Waygood in :gh:`105566` and :gh:`105570`.)
2005
2006 * Deprecate the :func:`typing.no_type_check_decorator` decorator function,
2007 to be removed in Python 3.15.
2008 After eight years in the :mod:`typing` module,
2009 it has yet to be supported by any major type checker.
2010 (Contributed by Alex Waygood in :gh:`106309`.)
2011
2012 * Deprecate :data:`typing.AnyStr`.
2013 In Python 3.16, it will be removed from ``typing.__all__``,
2014 and a :exc:`DeprecationWarning` will be emitted at runtime
2015 when it is imported or accessed.
2016 It will be removed entirely in Python 3.18.
2017 Use the new :ref:`type parameter syntax <type-params>` instead.
2018 (Contributed by Michael The in :gh:`107116`.)
2019
2020 * :mod:`wave`:
2021
2022 * Deprecate the :meth:`~wave.Wave_read.getmark`, :meth:`!setmark`,
2023 and :meth:`~wave.Wave_read.getmarkers` methods of
2024 the :class:`~wave.Wave_read` and :class:`~wave.Wave_write` classes,
2025 to be removed in Python 3.15.
2026 (Contributed by Victor Stinner in :gh:`105096`.)
2027
2028 .. Add deprecations above alphabetically, not here at the end.
2029
2030 .. include:: ../deprecations/pending-removal-in-3.14.rst
2031
2032 .. include:: ../deprecations/pending-removal-in-3.15.rst
2033
2034 .. include:: ../deprecations/pending-removal-in-3.16.rst
2035
2036 .. include:: ../deprecations/pending-removal-in-3.17.rst
2037
2038 .. include:: ../deprecations/pending-removal-in-3.18.rst
2039
2040 .. include:: ../deprecations/pending-removal-in-future.rst
2041
2042 CPython Bytecode Changes
2043 ========================
2044
2045 * The oparg of :opcode:`YIELD_VALUE` is now
2046 ``1`` if the yield is part of a yield-from or await, and ``0`` otherwise.
2047 The oparg of :opcode:`RESUME` was changed to add a bit indicating
2048 if the except-depth is 1, which is needed to optimize closing of generators.
2049 (Contributed by Irit Katriel in :gh:`111354`.)
2050
2051
2052 C API Changes
2053 =============
2054
2055 New Features
2056 ------------
2057
2058 * Add the :ref:`PyMonitoring C API <c-api-monitoring>`
2059 for generating :pep:`669` monitoring events:
2060
2061 * :c:type:`PyMonitoringState`
2062 * :c:func:`PyMonitoring_FirePyStartEvent`
2063 * :c:func:`PyMonitoring_FirePyResumeEvent`
2064 * :c:func:`PyMonitoring_FirePyReturnEvent`
2065 * :c:func:`PyMonitoring_FirePyYieldEvent`
2066 * :c:func:`PyMonitoring_FireCallEvent`
2067 * :c:func:`PyMonitoring_FireLineEvent`
2068 * :c:func:`PyMonitoring_FireJumpEvent`
2069 * :c:func:`PyMonitoring_FireBranchEvent`
2070 * :c:func:`PyMonitoring_FireCReturnEvent`
2071 * :c:func:`PyMonitoring_FirePyThrowEvent`
2072 * :c:func:`PyMonitoring_FireRaiseEvent`
2073 * :c:func:`PyMonitoring_FireCRaiseEvent`
2074 * :c:func:`PyMonitoring_FireReraiseEvent`
2075 * :c:func:`PyMonitoring_FireExceptionHandledEvent`
2076 * :c:func:`PyMonitoring_FirePyUnwindEvent`
2077 * :c:func:`PyMonitoring_FireStopIterationEvent`
2078 * :c:func:`PyMonitoring_EnterScope`
2079 * :c:func:`PyMonitoring_ExitScope`
2080
2081 (Contributed by Irit Katriel in :gh:`111997`).
2082
2083 * Add :c:type:`PyMutex`, a lightweight mutex that occupies a single byte,
2084 and the new :c:func:`PyMutex_Lock` and :c:func:`PyMutex_Unlock` functions.
2085 :c:func:`!PyMutex_Lock` will release the :term:`GIL` (if currently held)
2086 if the operation needs to block.
2087 (Contributed by Sam Gross in :gh:`108724`.)
2088
2089 * Add the :ref:`PyTime C API <c-api-time>` to provide access to system clocks:
2090
2091 * :c:type:`PyTime_t`.
2092 * :c:var:`PyTime_MIN` and :c:var:`PyTime_MAX`.
2093 * :c:func:`PyTime_AsSecondsDouble`.
2094 * :c:func:`PyTime_Monotonic`.
2095 * :c:func:`PyTime_MonotonicRaw`.
2096 * :c:func:`PyTime_PerfCounter`.
2097 * :c:func:`PyTime_PerfCounterRaw`.
2098 * :c:func:`PyTime_Time`.
2099 * :c:func:`PyTime_TimeRaw`.
2100
2101 (Contributed by Victor Stinner and Petr Viktorin in :gh:`110850`.)
2102
2103 * Add the :c:func:`PyDict_ContainsString` function
2104 with the same behavior as :c:func:`PyDict_Contains`,
2105 but *key* is specified as a :c:expr:`const char*` UTF-8 encoded bytes string,
2106 rather than a :c:expr:`PyObject*`.
2107 (Contributed by Victor Stinner in :gh:`108314`.)
2108
2109 * Add the :c:func:`PyDict_GetItemRef` and :c:func:`PyDict_GetItemStringRef`
2110 functions,
2111 which behave similarly to :c:func:`PyDict_GetItemWithError`,
2112 but return a :term:`strong reference` instead of a :term:`borrowed reference`.
2113 Moreover, these functions return ``-1`` on error,
2114 removing the need to check :c:func:`!PyErr_Occurred`.
2115 (Contributed by Victor Stinner in :gh:`106004`.)
2116
2117 * Add the :c:func:`PyDict_SetDefaultRef` function,
2118 which behaves similarly to :c:func:`PyDict_SetDefault`,
2119 but returns a :term:`strong reference` instead of a :term:`borrowed reference`.
2120 This function returns ``-1`` on error,
2121 ``0`` on insertion,
2122 and ``1`` if the key was already present in the dictionary.
2123 (Contributed by Sam Gross in :gh:`112066`.)
2124
2125 * Add the :c:func:`PyDict_Pop` and :c:func:`PyDict_PopString` functions
2126 to remove a key from a dictionary and optionally return the removed value.
2127 This is similar to :meth:`dict.pop`,
2128 though there is no default value,
2129 and :exc:`KeyError` is not raised for missing keys.
2130 (Contributed by Stefan Behnel and Victor Stinner in :gh:`111262`.)
2131
2132 * Add the :c:func:`PyMapping_GetOptionalItem`
2133 and :c:func:`PyMapping_GetOptionalItemString` functions
2134 as alternatives to :c:func:`PyObject_GetItem`
2135 and :c:func:`PyMapping_GetItemString` respectively.
2136 The new functions do not raise :exc:`KeyError`
2137 if the requested key is missing from the mapping.
2138 These variants are more convenient and faster
2139 if a missing key should not be treated as a failure.
2140 (Contributed by Serhiy Storchaka in :gh:`106307`.)
2141
2142 * Add the :c:func:`PyObject_GetOptionalAttr`
2143 and :c:func:`PyObject_GetOptionalAttrString` functions
2144 as alternatives to :c:func:`PyObject_GetAttr`
2145 and :c:func:`PyObject_GetAttrString` respectively.
2146 The new functions do not raise :exc:`AttributeError`
2147 if the requested attribute is not found on the object.
2148 These variants are more convenient and faster
2149 if the missing attribute should not be treated as a failure.
2150 (Contributed by Serhiy Storchaka in :gh:`106521`.)
2151
2152 * Add the :c:func:`PyErr_FormatUnraisable` function
2153 as an extension to :c:func:`PyErr_WriteUnraisable`
2154 that allows customizing the warning message.
2155 (Contributed by Serhiy Storchaka in :gh:`108082`.)
2156
2157 * Add new functions that return a :term:`strong reference` instead of
2158 a :term:`borrowed reference` for frame locals, globals, and builtins,
2159 as part of :ref:`PEP 667 <whatsnew313-locals-semantics>`:
2160
2161 * :c:func:`PyEval_GetFrameBuiltins` replaces :c:func:`PyEval_GetBuiltins`
2162 * :c:func:`PyEval_GetFrameGlobals` replaces :c:func:`PyEval_GetGlobals`
2163 * :c:func:`PyEval_GetFrameLocals` replaces :c:func:`PyEval_GetLocals`
2164
2165 (Contributed by Mark Shannon and Tian Gao in :gh:`74929`.)
2166
2167 * Add the :c:func:`Py_GetConstant` and :c:func:`Py_GetConstantBorrowed`
2168 functions to get :term:`strong <strong reference>`
2169 or :term:`borrowed <borrowed reference>` references to constants.
2170 For example, ``Py_GetConstant(Py_CONSTANT_ZERO)`` returns a strong reference
2171 to the constant zero.
2172 (Contributed by Victor Stinner in :gh:`115754`.)
2173
2174 * Add the :c:func:`PyImport_AddModuleRef` function
2175 as a replacement for :c:func:`PyImport_AddModule`
2176 that returns a :term:`strong reference` instead of a :term:`borrowed reference`.
2177 (Contributed by Victor Stinner in :gh:`105922`.)
2178
2179 * Add the :c:func:`Py_IsFinalizing` function to check
2180 whether the main Python interpreter is
2181 :term:`shutting down <interpreter shutdown>`.
2182 (Contributed by Victor Stinner in :gh:`108014`.)
2183
2184 * Add the :c:func:`PyList_GetItemRef` function
2185 as a replacement for :c:func:`PyList_GetItem`
2186 that returns a :term:`strong reference` instead of a :term:`borrowed reference`.
2187 (Contributed by Sam Gross in :gh:`114329`.)
2188
2189 * Add the :c:func:`PyList_Extend` and :c:func:`PyList_Clear` functions,
2190 mirroring the Python :meth:`list.extend` and :meth:`list.clear` methods.
2191 (Contributed by Victor Stinner in :gh:`111138`.)
2192
2193 * Add the :c:func:`PyLong_AsInt` function.
2194 It behaves similarly to :c:func:`PyLong_AsLong`,
2195 but stores the result in a C :c:expr:`int` instead of a C :c:expr:`long`.
2196 (Contributed by Victor Stinner in :gh:`108014`.)
2197
2198 * Add the :c:func:`PyLong_AsNativeBytes`, :c:func:`PyLong_FromNativeBytes`,
2199 and :c:func:`PyLong_FromUnsignedNativeBytes` functions
2200 to simplify converting between native integer types
2201 and Python :class:`int` objects.
2202 (Contributed by Steve Dower in :gh:`111140`.)
2203
2204 * Add :c:func:`PyModule_Add` function, which is similar to
2205 :c:func:`PyModule_AddObjectRef` and :c:func:`PyModule_AddObject`,
2206 but always steals a reference to the value.
2207 (Contributed by Serhiy Storchaka in :gh:`86493`.)
2208
2209 * Add the :c:func:`PyObject_GenericHash` function
2210 that implements the default hashing function of a Python object.
2211 (Contributed by Serhiy Storchaka in :gh:`113024`.)
2212
2213 * Add the :c:func:`Py_HashPointer` function to hash a raw pointer.
2214 (Contributed by Victor Stinner in :gh:`111545`.)
2215
2216 * Add the :c:func:`PyObject_VisitManagedDict` and
2217 :c:func:`PyObject_ClearManagedDict` functions.
2218 which must be called by the traverse and clear functions of a type using
2219 the :c:macro:`Py_TPFLAGS_MANAGED_DICT` flag.
2220 The `pythoncapi-compat project`_ can be used to
2221 use these functions with Python 3.11 and 3.12.
2222 (Contributed by Victor Stinner in :gh:`107073`.)
2223
2224 * Add the :c:func:`PyRefTracer_SetTracer`
2225 and :c:func:`PyRefTracer_GetTracer` functions,
2226 which enable tracking object creation and destruction
2227 in the same way that the :mod:`tracemalloc` module does.
2228 (Contributed by Pablo Galindo in :gh:`93502`.)
2229
2230 * Add the :c:func:`PySys_AuditTuple` function
2231 as an alternative to :c:func:`PySys_Audit`
2232 that takes event arguments as a Python :class:`tuple` object.
2233 (Contributed by Victor Stinner in :gh:`85283`.)
2234
2235 * Add the :c:func:`PyThreadState_GetUnchecked()` function
2236 as an alternative to :c:func:`PyThreadState_Get()`
2237 that doesn't kill the process with a fatal error if it is ``NULL``.
2238 The caller is responsible for checking if the result is ``NULL``.
2239 (Contributed by Victor Stinner in :gh:`108867`.)
2240
2241 * Add the :c:func:`PyType_GetFullyQualifiedName` function
2242 to get the type's fully qualified name.
2243 The module name is prepended if :attr:`type.__module__` is
2244 a string and is not equal to either ``'builtins'`` or ``'__main__'``.
2245 (Contributed by Victor Stinner in :gh:`111696`.)
2246
2247 * Add the :c:func:`PyType_GetModuleName` function
2248 to get the type's module name. This is equivalent to getting the
2249 :attr:`type.__module__` attribute.
2250 (Contributed by Eric Snow and Victor Stinner in :gh:`111696`.)
2251
2252 * Add the :c:func:`PyUnicode_EqualToUTF8AndSize`
2253 and :c:func:`PyUnicode_EqualToUTF8` functions
2254 to compare a Unicode object with a :c:expr:`const char*` UTF-8 encoded string
2255 and ``1`` if they are equal or ``0`` otherwise.
2256 These functions do not raise exceptions.
2257 (Contributed by Serhiy Storchaka in :gh:`110289`.)
2258
2259 * Add the :c:func:`PyWeakref_GetRef` function
2260 as an alternative to :c:func:`PyWeakref_GetObject`
2261 that returns a :term:`strong reference`
2262 or ``NULL`` if the referent is no longer live.
2263 (Contributed by Victor Stinner in :gh:`105927`.)
2264
2265 * Add fixed variants of functions which silently ignore errors:
2266
2267 * :c:func:`PyObject_HasAttrWithError` replaces :c:func:`PyObject_HasAttr`.
2268 * :c:func:`PyObject_HasAttrStringWithError`
2269 replaces :c:func:`PyObject_HasAttrString`.
2270 * :c:func:`PyMapping_HasKeyWithError` replaces :c:func:`PyMapping_HasKey`.
2271 * :c:func:`PyMapping_HasKeyStringWithError`
2272 replaces :c:func:`PyMapping_HasKeyString`.
2273
2274 The new functions return ``-1`` for errors
2275 and the standard ``1`` for true and ``0`` for false.
2276
2277 (Contributed by Serhiy Storchaka in :gh:`108511`.)
2278
2279
2280 Changed C APIs
2281 --------------
2282
2283 * The *keywords* parameter of :c:func:`PyArg_ParseTupleAndKeywords`
2284 and :c:func:`PyArg_VaParseTupleAndKeywords`
2285 now has type :c:expr:`char * const *` in C
2286 and :c:expr:`const char * const *` in C++,
2287 instead of :c:expr:`char **`.
2288 In C++, this makes these functions compatible with arguments
2289 of type :c:expr:`const char * const *`, :c:expr:`const char **`,
2290 or :c:expr:`char * const *` without an explicit type cast.
2291 In C, the functions only support arguments of type :c:expr:`char * const *`.
2292 This can be overridden with the :c:macro:`PY_CXX_CONST` macro.
2293 (Contributed by Serhiy Storchaka in :gh:`65210`.)
2294
2295 * :c:func:`PyArg_ParseTupleAndKeywords` now supports
2296 non-ASCII keyword parameter names.
2297 (Contributed by Serhiy Storchaka in :gh:`110815`.)
2298
2299 * The :c:func:`!PyCode_GetFirstFree` function is now unstable API
2300 and is now named :c:func:`PyUnstable_Code_GetFirstFree`.
2301 (Contributed by Bogdan Romanyuk in :gh:`115781`.)
2302
2303 * The :c:func:`PyDict_GetItem`, :c:func:`PyDict_GetItemString`,
2304 :c:func:`PyMapping_HasKey`, :c:func:`PyMapping_HasKeyString`,
2305 :c:func:`PyObject_HasAttr`, :c:func:`PyObject_HasAttrString`,
2306 and :c:func:`PySys_GetObject` functions,
2307 each of which clears all errors which occurred when calling them
2308 now reports these errors using :func:`sys.unraisablehook`.
2309 You may replace them with other functions as recommended in the documentation.
2310 (Contributed by Serhiy Storchaka in :gh:`106672`.)
2311
2312 * Add support for the ``%T``, ``%#T``, ``%N`` and ``%#N`` formats
2313 to :c:func:`PyUnicode_FromFormat`:
2314
2315 * ``%T``: Get the fully qualified name of an object type
2316 * ``%#T``: As above, but use a colon as the separator
2317 * ``%N``: Get the fully qualified name of a type
2318 * ``%#N``: As above, but use a colon as the separator
2319
2320 See :pep:`737` for more information.
2321 (Contributed by Victor Stinner in :gh:`111696`.)
2322
2323 * You no longer have to define the ``PY_SSIZE_T_CLEAN`` macro before
2324 including :file:`Python.h` when using ``#`` formats in
2325 :ref:`format codes <arg-parsing-string-and-buffers>`.
2326 APIs accepting the format codes always use ``Py_ssize_t`` for ``#`` formats.
2327 (Contributed by Inada Naoki in :gh:`104922`.)
2328
2329 * If Python is built in :ref:`debug mode <debug-build>`
2330 or :option:`with assertions <--with-assertions>`,
2331 :c:func:`PyTuple_SET_ITEM` and :c:func:`PyList_SET_ITEM`
2332 now check the index argument with an assertion.
2333 (Contributed by Victor Stinner in :gh:`106168`.)
2334
2335
2336 Limited C API Changes
2337 ---------------------
2338
2339 * The following functions are now included in the Limited C API:
2340
2341 * :c:func:`PyMem_RawMalloc`
2342 * :c:func:`PyMem_RawCalloc`
2343 * :c:func:`PyMem_RawRealloc`
2344 * :c:func:`PyMem_RawFree`
2345 * :c:func:`PySys_Audit`
2346 * :c:func:`PySys_AuditTuple`
2347 * :c:func:`PyType_GetModuleByDef`
2348
2349 (Contributed by Victor Stinner in :gh:`85283` and :gh:`116936`.)
2350
2351 * Python built with :option:`--with-trace-refs` (tracing references)
2352 now supports the :ref:`Limited API <limited-c-api>`.
2353 (Contributed by Victor Stinner in :gh:`108634`.)
2354
2355
2356 Removed C APIs
2357 --------------
2358
2359 * Remove several functions, macros, variables, etc
2360 with names prefixed by ``_Py`` or ``_PY`` (which are considered private).
2361 If your project is affected by one of these removals
2362 and you believe that the removed API should remain available,
2363 please :ref:`open a new issue <using-the-tracker>` to request a public C API
2364 and add ``cc: @vstinner`` to the issue to notify Victor Stinner.
2365 (Contributed by Victor Stinner in :gh:`106320`.)
2366
2367 * Remove old buffer protocols deprecated in Python 3.0.
2368 Use :ref:`bufferobjects` instead.
2369
2370 * :c:func:`!PyObject_CheckReadBuffer`:
2371 Use :c:func:`PyObject_CheckBuffer` to test
2372 whether the object supports the buffer protocol.
2373 Note that :c:func:`PyObject_CheckBuffer` doesn't guarantee
2374 that :c:func:`PyObject_GetBuffer` will succeed.
2375 To test if the object is actually readable,
2376 see the next example of :c:func:`PyObject_GetBuffer`.
2377
2378 * :c:func:`!PyObject_AsCharBuffer`, :c:func:`!PyObject_AsReadBuffer`:
2379 Use :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release` instead:
2380
2381 .. code-block:: c
2382
2383 Py_buffer view;
2384 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {
2385 return NULL;
2386 }
2387 // Use `view.buf` and `view.len` to read from the buffer.
2388 // You may need to cast buf as `(const char*)view.buf`.
2389 PyBuffer_Release(&view);
2390
2391 * :c:func:`!PyObject_AsWriteBuffer`:
2392 Use :c:func:`PyObject_GetBuffer` and :c:func:`PyBuffer_Release` instead:
2393
2394 .. code-block:: c
2395
2396 Py_buffer view;
2397 if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) {
2398 return NULL;
2399 }
2400 // Use `view.buf` and `view.len` to write to the buffer.
2401 PyBuffer_Release(&view);
2402
2403 (Contributed by Inada Naoki in :gh:`85275`.)
2404
2405 * Remove various functions deprecated in Python 3.9:
2406
2407 * :c:func:`!PyEval_CallObject`, :c:func:`!PyEval_CallObjectWithKeywords`:
2408 Use :c:func:`PyObject_CallNoArgs` or :c:func:`PyObject_Call` instead.
2409
2410 .. warning::
2411
2412 In :c:func:`PyObject_Call`, positional arguments must be a :class:`tuple`
2413 and must not be ``NULL``,
2414 and keyword arguments must be a :class:`dict` or ``NULL``,
2415 whereas the removed functions checked argument types
2416 and accepted ``NULL`` positional and keyword arguments.
2417 To replace ``PyEval_CallObjectWithKeywords(func, NULL, kwargs)`` with
2418 :c:func:`PyObject_Call`,
2419 pass an empty tuple as positional arguments using
2420 :c:func:`PyTuple_New(0) <PyTuple_New>`.
2421
2422 * :c:func:`!PyEval_CallFunction`:
2423 Use :c:func:`PyObject_CallFunction` instead.
2424 * :c:func:`!PyEval_CallMethod`:
2425 Use :c:func:`PyObject_CallMethod` instead.
2426 * :c:func:`!PyCFunction_Call`:
2427 Use :c:func:`PyObject_Call` instead.
2428
2429 (Contributed by Victor Stinner in :gh:`105107`.)
2430
2431 * Remove the following old functions to configure the Python initialization,
2432 deprecated in Python 3.11:
2433
2434 * :c:func:`!PySys_AddWarnOptionUnicode`:
2435 Use :c:member:`PyConfig.warnoptions` instead.
2436 * :c:func:`!PySys_AddWarnOption`:
2437 Use :c:member:`PyConfig.warnoptions` instead.
2438 * :c:func:`!PySys_AddXOption`:
2439 Use :c:member:`PyConfig.xoptions` instead.
2440 * :c:func:`!PySys_HasWarnOptions`:
2441 Use :c:member:`PyConfig.xoptions` instead.
2442 * :c:func:`!PySys_SetPath`:
2443 Set :c:member:`PyConfig.module_search_paths` instead.
2444 * :c:func:`!Py_SetPath`:
2445 Set :c:member:`PyConfig.module_search_paths` instead.
2446 * :c:func:`!Py_SetStandardStreamEncoding`:
2447 Set :c:member:`PyConfig.stdio_encoding` instead,
2448 and set also maybe :c:member:`PyConfig.legacy_windows_stdio` (on Windows).
2449 * :c:func:`!_Py_SetProgramFullPath`:
2450 Set :c:member:`PyConfig.executable` instead.
2451
2452 Use the new :c:type:`PyConfig` API of the :ref:`Python Initialization
2453 Configuration <init-config>` instead (:pep:`587`), added to Python 3.8.
2454 (Contributed by Victor Stinner in :gh:`105145`.)
2455
2456 * Remove :c:func:`!PyEval_AcquireLock` and :c:func:`!PyEval_ReleaseLock` functions,
2457 deprecated in Python 3.2.
2458 They didn't update the current thread state.
2459 They can be replaced with:
2460
2461 * :c:func:`PyEval_SaveThread` and :c:func:`PyEval_RestoreThread`;
2462 * low-level :c:func:`PyEval_AcquireThread` and :c:func:`PyEval_RestoreThread`;
2463 * or :c:func:`PyGILState_Ensure` and :c:func:`PyGILState_Release`.
2464
2465 (Contributed by Victor Stinner in :gh:`105182`.)
2466
2467 * Remove the :c:func:`!PyEval_ThreadsInitialized` function,
2468 deprecated in Python 3.9.
2469 Since Python 3.7, :c:func:`!Py_Initialize` always creates the GIL:
2470 calling :c:func:`!PyEval_InitThreads` does nothing and
2471 :c:func:`!PyEval_ThreadsInitialized` always returns non-zero.
2472 (Contributed by Victor Stinner in :gh:`105182`.)
2473
2474 * Remove the :c:func:`!_PyInterpreterState_Get` alias to
2475 :c:func:`PyInterpreterState_Get()`
2476 which was kept for backward compatibility with Python 3.8.
2477 The `pythoncapi-compat project`_ can be used to get
2478 :c:func:`PyInterpreterState_Get()` on Python 3.8 and older.
2479 (Contributed by Victor Stinner in :gh:`106320`.)
2480
2481 * Remove the private :c:func:`!_PyObject_FastCall` function:
2482 use :c:func:`!PyObject_Vectorcall` which is available since Python 3.8
2483 (:pep:`590`).
2484 (Contributed by Victor Stinner in :gh:`106023`.)
2485
2486 * Remove the ``cpython/pytime.h`` header file,
2487 which only contained private functions.
2488 (Contributed by Victor Stinner in :gh:`106316`.)
2489
2490 * Remove the undocumented ``PY_TIMEOUT_MAX`` constant from the limited C API.
2491 (Contributed by Victor Stinner in :gh:`110014`.)
2492
2493 * Remove the old trashcan macros ``Py_TRASHCAN_SAFE_BEGIN``
2494 and ``Py_TRASHCAN_SAFE_END``.
2495 Replace both with the new macros ``Py_TRASHCAN_BEGIN``
2496 and ``Py_TRASHCAN_END``.
2497 (Contributed by Irit Katriel in :gh:`105111`.)
2498
2499 Deprecated C APIs
2500 -----------------
2501
2502 * Deprecate old Python initialization functions:
2503
2504 * :c:func:`PySys_ResetWarnOptions`:
2505 Clear :data:`sys.warnoptions` and :data:`!warnings.filters` instead.
2506 * :c:func:`Py_GetExecPrefix`:
2507 Get :data:`sys.exec_prefix` instead.
2508 * :c:func:`Py_GetPath`:
2509 Get :data:`sys.path` instead.
2510 * :c:func:`Py_GetPrefix`:
2511 Get :data:`sys.prefix` instead.
2512 * :c:func:`Py_GetProgramFullPath`:
2513 Get :data:`sys.executable` instead.
2514 * :c:func:`Py_GetProgramName`:
2515 Get :data:`sys.executable` instead.
2516 * :c:func:`Py_GetPythonHome`:
2517 Get :c:member:`PyConfig.home`
2518 or the :envvar:`PYTHONHOME` environment variable instead.
2519
2520 (Contributed by Victor Stinner in :gh:`105145`.)
2521
2522 * :term:`Soft deprecate <soft deprecated>` the
2523 :c:func:`PyEval_GetBuiltins`, :c:func:`PyEval_GetGlobals`,
2524 and :c:func:`PyEval_GetLocals` functions,
2525 which return a :term:`borrowed reference`.
2526 (Soft deprecated as part of :pep:`667`.)
2527
2528 * Deprecate the :c:func:`PyImport_ImportModuleNoBlock` function,
2529 which is just an alias to :c:func:`PyImport_ImportModule` since Python 3.3.
2530 (Contributed by Victor Stinner in :gh:`105396`.)
2531
2532 * :term:`Soft deprecate <soft deprecated>` the
2533 :c:func:`PyModule_AddObject` function.
2534 It should be replaced with :c:func:`PyModule_Add`
2535 or :c:func:`PyModule_AddObjectRef`.
2536 (Contributed by Serhiy Storchaka in :gh:`86493`.)
2537
2538 * Deprecate the old ``Py_UNICODE`` and ``PY_UNICODE_TYPE`` types
2539 and the :c:macro:`!Py_UNICODE_WIDE` define.
2540 Use the :c:type:`wchar_t` type directly instead.
2541 Since Python 3.3, ``Py_UNICODE`` and ``PY_UNICODE_TYPE``
2542 are just aliases to :c:type:`!wchar_t`.
2543 (Contributed by Victor Stinner in :gh:`105156`.)
2544
2545 * Deprecate the :c:func:`PyWeakref_GetObject` and
2546 :c:func:`PyWeakref_GET_OBJECT` functions,
2547 which return a :term:`borrowed reference`.
2548 Replace them with the new :c:func:`PyWeakref_GetRef` function,
2549 which returns a :term:`strong reference`.
2550 The `pythoncapi-compat project`_ can be used to get
2551 :c:func:`PyWeakref_GetRef` on Python 3.12 and older.
2552 (Contributed by Victor Stinner in :gh:`105927`.)
2553
2554 .. Add deprecations above alphabetically, not here at the end.
2555
2556 .. include:: ../deprecations/c-api-pending-removal-in-3.14.rst
2557
2558 .. include:: ../deprecations/c-api-pending-removal-in-3.15.rst
2559
2560 .. include:: ../deprecations/c-api-pending-removal-in-3.16.rst
2561
2562 .. include:: ../deprecations/c-api-pending-removal-in-future.rst
2563
2564 .. _pythoncapi-compat project: https://github.com/python/pythoncapi-compat/
2565
2566 Build Changes
2567 =============
2568
2569 * ``arm64-apple-ios`` and ``arm64-apple-ios-simulator`` are both
2570 now :pep:`11` tier 3 platforms.
2571 (:ref:`PEP 730 <whatsnew313-platform-support>` written
2572 and implementation contributed by Russell Keith-Magee in :gh:`114099`.)
2573
2574 * ``aarch64-linux-android`` and ``x86_64-linux-android`` are both
2575 now :pep:`11` tier 3 platforms.
2576 (:ref:`PEP 738 <whatsnew313-platform-support>` written
2577 and implementation contributed by Malcolm Smith in :gh:`116622`.)
2578
2579 * ``wasm32-wasi`` is now a :pep:`11` tier 2 platform.
2580 (Contributed by Brett Cannon in :gh:`115192`.)
2581
2582 * ``wasm32-emscripten`` is no longer a :pep:`11` supported platform.
2583 (Contributed by Brett Cannon in :gh:`115192`.)
2584
2585 * Building CPython now requires a compiler with support for the C11 atomic
2586 library, GCC built-in atomic functions, or MSVC interlocked intrinsics.
2587
2588 * Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate
2589 the :file:`configure` script.
2590 (Contributed by Christian Heimes in :gh:`89886` and by Victor Stinner in :gh:`112090`.)
2591
2592 * SQLite 3.15.2 or newer is required to build
2593 the :mod:`sqlite3` extension module.
2594 (Contributed by Erlend Aasland in :gh:`105875`.)
2595
2596 * CPython now bundles the `mimalloc library`_ by default.
2597 It is licensed under the MIT license;
2598 see :ref:`mimalloc license <mimalloc-license>`.
2599 The bundled mimalloc has custom changes, see :gh:`113141` for details.
2600 (Contributed by Dino Viehland in :gh:`109914`.)
2601
2602 .. _mimalloc library: https://github.com/microsoft/mimalloc/
2603
2604 * The :file:`configure` option :option:`--with-system-libmpdec`
2605 now defaults to ``yes``.
2606 The bundled copy of ``libmpdec`` will be removed in Python 3.16.
2607
2608 * Python built with :file:`configure` :option:`--with-trace-refs`
2609 (tracing references) is now ABI compatible with the Python release build
2610 and :ref:`debug build <debug-build>`.
2611 (Contributed by Victor Stinner in :gh:`108634`.)
2612
2613 * On POSIX systems, the pkg-config (``.pc``) filenames now include the ABI
2614 flags. For example, the free-threaded build generates ``python-3.13t.pc``
2615 and the debug build generates ``python-3.13d.pc``.
2616
2617 * The ``errno``, ``fcntl``, ``grp``, ``md5``, ``pwd``, ``resource``,
2618 ``termios``, ``winsound``,
2619 ``_ctypes_test``, ``_multiprocessing.posixshmem``, ``_scproxy``, ``_stat``,
2620 ``_statistics``, ``_testconsole``, ``_testimportmultiple`` and ``_uuid``
2621 C extensions are now built with the :ref:`limited C API <limited-c-api>`.
2622 (Contributed by Victor Stinner in :gh:`85283`.)
2623
2624
2625 Porting to Python 3.13
2626 ======================
2627
2628 This section lists previously described changes and other bugfixes
2629 that may require changes to your code.
2630
2631 Changes in the Python API
2632 -------------------------
2633
2634 .. _pep667-porting-notes-py:
2635
2636 * :ref:`PEP 667 <whatsnew313-locals-semantics>` introduces several changes
2637 to the semantics of :func:`locals` and :attr:`f_locals <frame.f_locals>`:
2638
2639 * Calling :func:`locals` in an :term:`optimized scope` now produces an
2640 independent snapshot on each call, and hence no longer implicitly updates
2641 previously returned references. Obtaining the legacy CPython behavior now
2642 requires explicit calls to update the initially returned dictionary with the
2643 results of subsequent calls to :func:`!locals`. Code execution functions that
2644 implicitly target :func:`!locals` (such as ``exec`` and ``eval``) must be
2645 passed an explicit namespace to access their results in an optimized scope.
2646 (Changed as part of :pep:`667`.)
2647
2648 * Calling :func:`locals` from a comprehension at module or class scope
2649 (including via ``exec`` or ``eval``) once more behaves as if the comprehension
2650 were running as an independent nested function (i.e. the local variables from
2651 the containing scope are not included). In Python 3.12, this had changed
2652 to include the local variables from the containing scope when implementing
2653 :pep:`709`. (Changed as part of :pep:`667`.)
2654
2655 * Accessing :attr:`FrameType.f_locals <frame.f_locals>` in an
2656 :term:`optimized scope` now returns a write-through proxy rather than a
2657 snapshot that gets updated at ill-specified times. If a snapshot is desired,
2658 it must be created explicitly with ``dict`` or the proxy's ``.copy()`` method.
2659 (Changed as part of :pep:`667`.)
2660
2661 * :class:`functools.partial` now emits a :exc:`FutureWarning`
2662 when used as a method.
2663 The behavior will change in future Python versions.
2664 Wrap it in :func:`staticmethod` if you want to preserve the old behavior.
2665 (Contributed by Serhiy Storchaka in :gh:`121027`.)
2666
2667 * An :exc:`OSError` is now raised by :func:`getpass.getuser`
2668 for any failure to retrieve a username,
2669 instead of :exc:`ImportError` on non-Unix platforms
2670 or :exc:`KeyError` on Unix platforms where the password database is empty.
2671
2672 * The value of the :attr:`!mode` attribute of :class:`gzip.GzipFile`
2673 is now a string (``'rb'`` or ``'wb'``) instead of an integer (``1`` or ``2``).
2674 The value of the :attr:`!mode` attribute of the readable file-like object
2675 returned by :meth:`zipfile.ZipFile.open` is now ``'rb'`` instead of ``'r'``.
2676 (Contributed by Serhiy Storchaka in :gh:`115961`.)
2677
2678 * :class:`mailbox.Maildir` now ignores files with a leading dot (``.``).
2679 (Contributed by Zackery Spytz in :gh:`65559`.)
2680
2681 * :meth:`pathlib.Path.glob` and :meth:`~pathlib.Path.rglob` now return both
2682 files and directories if a pattern that ends with "``**``" is given,
2683 rather than directories only.
2684 Add a trailing slash to keep the previous behavior and only match directories.
2685
2686 * The :mod:`threading` module now expects the :mod:`!_thread` module
2687 to have an :func:`!_is_main_interpreter` function.
2688 This function takes no arguments and returns ``True``
2689 if the current interpreter is the main interpreter.
2690
2691 Any library or application that provides a custom :mod:`!_thread` module
2692 must provide :func:`!_is_main_interpreter`,
2693 just like the module's other "private" attributes.
2694 (:gh:`112826`.)
2695
2696
2697 Changes in the C API
2698 --------------------
2699
2700 * ``Python.h`` no longer includes the ``<ieeefp.h>`` standard header. It was
2701 included for the :c:func:`!finite` function which is now provided by the
2702 ``<math.h>`` header. It should now be included explicitly if needed. Remove
2703 also the ``HAVE_IEEEFP_H`` macro.
2704 (Contributed by Victor Stinner in :gh:`108765`.)
2705
2706 * ``Python.h`` no longer includes these standard header files: ``<time.h>``,
2707 ``<sys/select.h>`` and ``<sys/time.h>``. If needed, they should now be
2708 included explicitly. For example, ``<time.h>`` provides the :c:func:`!clock` and
2709 :c:func:`!gmtime` functions, ``<sys/select.h>`` provides the :c:func:`!select`
2710 function, and ``<sys/time.h>`` provides the :c:func:`!futimes`, :c:func:`!gettimeofday`
2711 and :c:func:`!setitimer` functions.
2712 (Contributed by Victor Stinner in :gh:`108765`.)
2713
2714 * On Windows, ``Python.h`` no longer includes the ``<stddef.h>`` standard
2715 header file. If needed, it should now be included explicitly. For example, it
2716 provides :c:func:`!offsetof` function, and ``size_t`` and ``ptrdiff_t`` types.
2717 Including ``<stddef.h>`` explicitly was already needed by all other
2718 platforms, the ``HAVE_STDDEF_H`` macro is only defined on Windows.
2719 (Contributed by Victor Stinner in :gh:`108765`.)
2720
2721 * If the :c:macro:`Py_LIMITED_API` macro is defined, :c:macro:`!Py_BUILD_CORE`,
2722 :c:macro:`!Py_BUILD_CORE_BUILTIN` and :c:macro:`!Py_BUILD_CORE_MODULE` macros
2723 are now undefined by ``<Python.h>``.
2724 (Contributed by Victor Stinner in :gh:`85283`.)
2725
2726 * The old trashcan macros ``Py_TRASHCAN_SAFE_BEGIN`` and ``Py_TRASHCAN_SAFE_END``
2727 were removed. They should be replaced by the new macros ``Py_TRASHCAN_BEGIN``
2728 and ``Py_TRASHCAN_END``.
2729
2730 A ``tp_dealloc`` function that has the old macros, such as::
2731
2732 static void
2733 mytype_dealloc(mytype *p)
2734 {
2735 PyObject_GC_UnTrack(p);
2736 Py_TRASHCAN_SAFE_BEGIN(p);
2737 ...
2738 Py_TRASHCAN_SAFE_END
2739 }
2740
2741 should migrate to the new macros as follows::
2742
2743 static void
2744 mytype_dealloc(mytype *p)
2745 {
2746 PyObject_GC_UnTrack(p);
2747 Py_TRASHCAN_BEGIN(p, mytype_dealloc)
2748 ...
2749 Py_TRASHCAN_END
2750 }
2751
2752 Note that ``Py_TRASHCAN_BEGIN`` has a second argument which
2753 should be the deallocation function it is in. The new macros were
2754 added in Python 3.8 and the old macros were deprecated in Python 3.11.
2755 (Contributed by Irit Katriel in :gh:`105111`.)
2756
2757 .. _pep667-porting-notes-c:
2758
2759 * :ref:`PEP 667 <whatsnew313-locals-semantics>` introduces several changes
2760 to frame-related functions:
2761
2762 * The effects of mutating the dictionary returned from
2763 :c:func:`PyEval_GetLocals` in an :term:`optimized scope` have changed.
2764 New dict entries added this way will now *only* be visible to
2765 subsequent :c:func:`PyEval_GetLocals` calls in that frame,
2766 as :c:func:`PyFrame_GetLocals`, :func:`locals`,
2767 and :attr:`FrameType.f_locals <frame.f_locals>` no longer access
2768 the same underlying cached dictionary.
2769 Changes made to entries for actual variable names and names added via
2770 the write-through proxy interfaces will be overwritten on subsequent calls
2771 to :c:func:`PyEval_GetLocals` in that frame.
2772 The recommended code update depends on how the function was being used,
2773 so refer to the deprecation notice on the function for details.
2774
2775 * Calling :c:func:`PyFrame_GetLocals` in an :term:`optimized scope`
2776 now returns a write-through proxy rather than a snapshot
2777 that gets updated at ill-specified times.
2778 If a snapshot is desired, it must be created explicitly
2779 (e.g. with :c:func:`PyDict_Copy`),
2780 or by calling the new :c:func:`PyEval_GetFrameLocals` API.
2781
2782 * :c:func:`!PyFrame_FastToLocals` and :c:func:`!PyFrame_FastToLocalsWithError`
2783 no longer have any effect.
2784 Calling these functions has been redundant since Python 3.11,
2785 when :c:func:`PyFrame_GetLocals` was first introduced.
2786
2787 * :c:func:`!PyFrame_LocalsToFast` no longer has any effect.
2788 Calling this function is redundant now that :c:func:`PyFrame_GetLocals`
2789 returns a write-through proxy for :term:`optimized scopes <optimized scope>`.
2790
2791 * Python 3.13 removed many private functions. Some of them can be replaced using these
2792 alternatives:
2793
2794 * ``_PyDict_Pop()``: :c:func:`PyDict_Pop` or :c:func:`PyDict_PopString`;
2795 * ``_PyDict_GetItemWithError()``: :c:func:`PyDict_GetItemRef`;
2796 * ``_PyErr_WriteUnraisableMsg()``: :c:func:`PyErr_FormatUnraisable`;
2797 * ``_PyEval_SetTrace()``: :c:func:`PyEval_SetTrace` or :c:func:`PyEval_SetTraceAllThreads`;
2798 * ``_PyList_Extend()``: :c:func:`PyList_Extend`;
2799 * ``_PyLong_AsInt()``: :c:func:`PyLong_AsInt`;
2800 * ``_PyMem_RawStrdup()``: ``strdup()``;
2801 * ``_PyMem_Strdup()``: ``strdup()``;
2802 * ``_PyObject_ClearManagedDict()``: :c:func:`PyObject_ClearManagedDict`;
2803 * ``_PyObject_VisitManagedDict()``: :c:func:`PyObject_VisitManagedDict`;
2804 * ``_PyThreadState_UncheckedGet()``: :c:func:`PyThreadState_GetUnchecked()`;
2805 * ``_PyTime_AsSecondsDouble()``: :c:func:`PyTime_AsSecondsDouble`;
2806 * ``_PyTime_GetMonotonicClock()``: :c:func:`PyTime_Monotonic` or :c:func:`PyTime_MonotonicRaw`;
2807 * ``_PyTime_GetPerfCounter()``: :c:func:`PyTime_PerfCounter` or :c:func:`PyTime_PerfCounterRaw`;
2808 * ``_PyTime_GetSystemClock()``: :c:func:`PyTime_Time` or :c:func:`PyTime_TimeRaw`;
2809 * ``_PyTime_MAX``: :c:var:`PyTime_MAX`;
2810 * ``_PyTime_MIN``: :c:var:`PyTime_MIN`;
2811 * ``_PyTime_t``: :c:type:`PyTime_t`;
2812 * ``_Py_HashPointer()``: :c:func:`Py_HashPointer`;
2813 * ``_Py_IsFinalizing()``: :c:func:`Py_IsFinalizing`.
2814
2815 The `pythoncapi-compat project`_ can be used to get most of these new
2816 functions on Python 3.12 and older.
2817
2818 Regression Test Changes
2819 =======================
2820
2821 * Python built with :file:`configure` :option:`--with-pydebug` now
2822 supports a :option:`-X presite=package.module <-X>` command-line
2823 option. If used, it specifies a module that should be imported early
2824 in the lifecycle of the interpreter, before ``site.py`` is executed.
2825 (Contributed by Łukasz Langa in :gh:`110769`.)
2826
2827
2828 Notable changes in 3.13.1
2829 =========================
2830
2831 sys
2832 ---
2833
2834 * The previously undocumented special function :func:`sys.getobjects`,
2835 which only exists in specialized builds of Python, may now return objects
2836 from other interpreters than the one it's called in.
2837
2838 Notable changes in 3.13.4
2839 =========================
2840
2841 os.path
2842 -------
2843
2844 * The *strict* parameter to :func:`os.path.realpath` accepts a new value,
2845 :data:`os.path.ALLOW_MISSING`.
2846 If used, errors other than :exc:`FileNotFoundError` will be re-raised;
2847 the resulting path can be missing but it will be free of symlinks.
2848 (Contributed by Petr Viktorin for :cve:`2025-4517`.)
2849
2850 tarfile
2851 -------
2852
2853 * :func:`~tarfile.data_filter` now normalizes symbolic link targets in order to
2854 avoid path traversal attacks.
2855 (Contributed by Petr Viktorin in :gh:`127987` and :cve:`2025-4138`.)
2856 * :func:`~tarfile.TarFile.extractall` now skips fixing up directory attributes
2857 when a directory was removed or replaced by another kind of file.
2858 (Contributed by Petr Viktorin in :gh:`127987` and :cve:`2024-12718`.)
2859 * :func:`~tarfile.TarFile.extract` and :func:`~tarfile.TarFile.extractall`
2860 now (re-)apply the extraction filter when substituting a link (hard or
2861 symbolic) with a copy of another archive member, and when fixing up
2862 directory attributes.
2863 The former raises a new exception, :exc:`~tarfile.LinkFallbackError`.
2864 (Contributed by Petr Viktorin for :cve:`2025-4330` and :cve:`2024-12718`.)
2865 * :func:`~tarfile.TarFile.extract` and :func:`~tarfile.TarFile.extractall`
2866 no longer extract rejected members when
2867 :func:`~tarfile.TarFile.errorlevel` is zero.
2868 (Contributed by Matt Prodani and Petr Viktorin in :gh:`112887`
2869 and :cve:`2025-4435`.)