ITookAPill's picture
PyComp First Commit
9273228
|
Raw
History Blame Contribute Delete
183 kB

A newer version of the Gradio SDK is available: 6.22.0

Upgrade

What's New In Python 3.13

Editors : Adam Turner and Thomas Wouters

* Anyone can add text to this document. Do not spend very much time on the wording of your changes, because your text will probably get rewritten to some degree.

* The maintainer will go through Misc/NEWS periodically and add changes; it's therefore more important to add your changes to Misc/NEWS than to this file.

* This is not a complete list of every single change; completeness is the purpose of Misc/NEWS. Some changes I consider too small or esoteric to include. If such a change is added to the text, I'll just remove it. (This is another reason you shouldn't spend too much time on writing your addition.)

* If you want to draw your new text to the attention of the maintainer, add 'XXX' to the beginning of the paragraph or section.

* It's OK to just add a fragmentary note about a change. For example: "XXX Describe the transmogrify() function added to the socket module." The maintainer will research the change and write the necessary text.

* You can comment out your additions if you like, but it's not necessary (especially when a final release is some months away).

* Credit the author of a patch or bugfix. Just the name is sufficient; the e-mail address isn't necessary.

  • It's helpful to add the issue number as a comment:

XXX Describe the transmogrify() function added to the socket module. (Contributed by P.Y. Developer in 12345{.interpreted-text role="gh"}.)

This saves the maintainer the effort of going through the VCS log when researching a change.

This article explains the new features in Python 3.13, compared to 3.12. Python 3.13 was released on October 7, 2024. For full details, see the changelog <changelog>{.interpreted-text role="ref"}.

::: seealso 719{.interpreted-text role="pep"} -- Python 3.13 Release Schedule :::

Summary -- Release Highlights

Python 3.13 is a stable release of the Python programming language, with a mix of changes to the language, the implementation and the standard library. The biggest changes include a new interactive interpreter, experimental support for running in a free-threaded mode (703{.interpreted-text role="pep"}), and a Just-In-Time compiler (744{.interpreted-text role="pep"}).

Error messages continue to improve, with tracebacks now highlighted in color by default. The locals{.interpreted-text role="func"} builtin now has defined semantics <whatsnew313-locals-semantics>{.interpreted-text role="ref"} for changing the returned mapping, and type parameters now support default values.

The library changes contain removal of deprecated APIs and modules, as well as the usual improvements in user-friendliness and correctness. Several legacy standard library modules have now been removed following their deprecation in Python 3.11 (594{.interpreted-text role="pep"}).

This article doesn't attempt to provide a complete specification of all new features, but instead gives a convenient overview. For full details refer to the documentation, such as the Library Reference <library-index>{.interpreted-text role="ref"} and Language Reference <reference-index>{.interpreted-text role="ref"}. To understand the complete implementation and design rationale for a change, refer to the PEP for a particular new feature; but note that PEPs usually are not kept up-to-date once a feature has been fully implemented. See Porting to Python 3.13 for guidance on upgrading from earlier versions of Python.


Interpreter improvements:

  • A greatly improved interactive interpreter <whatsnew313-better-interactive-interpreter>{.interpreted-text role="ref"} and improved error messages <whatsnew313-improved-error-messages>{.interpreted-text role="ref"}.
  • 667{.interpreted-text role="pep"}: The locals{.interpreted-text role="func"} builtin now has defined semantics <whatsnew313-locals-semantics>{.interpreted-text role="ref"} when mutating the returned mapping. Python debuggers and similar tools may now more reliably update local variables in optimized scopes even during concurrent code execution.
  • 703{.interpreted-text role="pep"}: CPython 3.13 has experimental support for running with the global interpreter lock{.interpreted-text role="term"} disabled. See Free-threaded CPython <whatsnew313-free-threaded-cpython>{.interpreted-text role="ref"} for more details.
  • 744{.interpreted-text role="pep"}: A basic JIT compiler <whatsnew313-jit-compiler>{.interpreted-text role="ref"} was added. It is currently disabled by default (though we may turn it on later). Performance improvements are modest -- we expect to improve this over the next few releases.
  • Color support in the new interactive interpreter <whatsnew313-better-interactive-interpreter>{.interpreted-text role="ref"}, as well as in tracebacks <whatsnew313-improved-error-messages>{.interpreted-text role="ref"} and doctest <whatsnew313-doctest>{.interpreted-text role="ref"} output. This can be disabled through the PYTHON_COLORS{.interpreted-text role="envvar"} and |NO_COLOR| environment variables.

Python data model improvements:

  • ~type.__static_attributes__{.interpreted-text role="attr"} stores the names of attributes accessed through self.X in any function in a class body.
  • ~type.__firstlineno__{.interpreted-text role="attr"} records the first line number of a class definition.

Significant improvements in the standard library:

  • Add a new PythonFinalizationError{.interpreted-text role="exc"} exception, raised when an operation is blocked during finalization <interpreter shutdown>{.interpreted-text role="term"}.
  • The argparse{.interpreted-text role="mod"} module now supports deprecating command-line options, positional arguments, and subcommands.
  • The new functions base64.z85encode{.interpreted-text role="func"} and base64.z85decode{.interpreted-text role="func"} support encoding and decoding Z85 data.
  • The copy{.interpreted-text role="mod"} module now has a copy.replace{.interpreted-text role="func"} function, with support for many builtin types and any class defining the ~object.__replace__{.interpreted-text role="func"} method.
  • The new dbm.sqlite3{.interpreted-text role="mod"} module is now the default dbm{.interpreted-text role="mod"} backend.
  • The os{.interpreted-text role="mod"} module has a suite of new functions <os-timerfd>{.interpreted-text role="ref"} for working with Linux's timer notification file descriptors.
  • The random{.interpreted-text role="mod"} module now has a command-line interface <random-cli>{.interpreted-text role="ref"}.

Security improvements:

  • ssl.create_default_context{.interpreted-text role="func"} sets ssl.VERIFY_X509_PARTIAL_CHAIN{.interpreted-text role="data"} and ssl.VERIFY_X509_STRICT{.interpreted-text role="data"} as default flags.

C API improvements:

  • The Py_mod_gil{.interpreted-text role="c:data"} slot is now used to indicate that an extension module supports running with the GIL{.interpreted-text role="term"} disabled.
  • The PyTime C API </c-api/time>{.interpreted-text role="doc"} has been added, providing access to system clocks.
  • PyMutex{.interpreted-text role="c:type"} is a new lightweight mutex that occupies a single byte.
  • There is a new suite of functions <c-api-monitoring>{.interpreted-text role="ref"} for generating 669{.interpreted-text role="pep"} monitoring events in the C API.

New typing features:

  • 696{.interpreted-text role="pep"}: Type parameters (typing.TypeVar{.interpreted-text role="data"}, typing.ParamSpec{.interpreted-text role="data"}, and typing.TypeVarTuple{.interpreted-text role="data"}) now support defaults.
  • 702{.interpreted-text role="pep"}: The new warnings.deprecated{.interpreted-text role="func"} decorator adds support for marking deprecations in the type system and at runtime.
  • 705{.interpreted-text role="pep"}: typing.ReadOnly{.interpreted-text role="data"} can be used to mark an item of a typing.TypedDict{.interpreted-text role="class"} as read-only for type checkers.
  • 742{.interpreted-text role="pep"}: typing.TypeIs{.interpreted-text role="data"} provides more intuitive type narrowing behavior, as an alternative to typing.TypeGuard{.interpreted-text role="data"}.

Platform support:

  • 730{.interpreted-text role="pep"}: Apple's iOS is now an officially supported platform <whatsnew313-platform-support>{.interpreted-text role="ref"}, at tier 3 <11#tier-3>{.interpreted-text role="pep"}.
  • 738{.interpreted-text role="pep"}: Android is now an officially supported platform <whatsnew313-platform-support>{.interpreted-text role="ref"}, at tier 3 <11#tier-3>{.interpreted-text role="pep"}.
  • wasm32-wasi is now supported as a tier 2 <11#tier-2>{.interpreted-text role="pep"} platform.
  • wasm32-emscripten is no longer an officially supported platform.

Important removals:

  • PEP 594 <whatsnew313-pep594>{.interpreted-text role="ref"}: The remaining 19 "dead batteries" (legacy stdlib modules) have been removed from the standard library: !aifc{.interpreted-text role="mod"}, !audioop{.interpreted-text role="mod"}, !cgi{.interpreted-text role="mod"}, !cgitb{.interpreted-text role="mod"}, !chunk{.interpreted-text role="mod"}, !crypt{.interpreted-text role="mod"}, !imghdr{.interpreted-text role="mod"}, !mailcap{.interpreted-text role="mod"}, !msilib{.interpreted-text role="mod"}, !nis{.interpreted-text role="mod"}, !nntplib{.interpreted-text role="mod"}, !ossaudiodev{.interpreted-text role="mod"}, !pipes{.interpreted-text role="mod"}, !sndhdr{.interpreted-text role="mod"}, !spwd{.interpreted-text role="mod"}, !sunau{.interpreted-text role="mod"}, !telnetlib{.interpreted-text role="mod"}, !uu{.interpreted-text role="mod"} and !xdrlib{.interpreted-text role="mod"}.
  • Remove the 2to3{.interpreted-text role="program"} tool and !lib2to3{.interpreted-text role="mod"} module (deprecated in Python 3.11).
  • Remove the !tkinter.tix{.interpreted-text role="mod"} module (deprecated in Python 3.6).
  • Remove the !locale.resetlocale{.interpreted-text role="func"} function.
  • Remove the !typing.io{.interpreted-text role="mod"} and !typing.re{.interpreted-text role="mod"} namespaces.
  • Remove chained classmethod{.interpreted-text role="class"} descriptors.

Release schedule changes:

602{.interpreted-text role="pep"} ("Annual Release Cycle for Python") has been updated to extend the full support ('bugfix') period for new releases to two years. This updated policy means that:

  • Python 3.9--3.12 have one and a half years of full support, followed by three and a half years of security fixes.
  • Python 3.13 and later have two years of full support, followed by three years of security fixes.

New Features

A better interactive interpreter {#whatsnew313-better-interactive-interpreter}

Python now uses a new interactive{.interpreted-text role="term"} shell by default, based on code from the PyPy project. When the user starts the REPL{.interpreted-text role="term"} from an interactive terminal, the following new features are now supported:

  • Multiline editing with history preservation.
  • Direct support for REPL-specific commands like help{.interpreted-text role="kbd"}, exit{.interpreted-text role="kbd"}, and quit{.interpreted-text role="kbd"}, without the need to call them as functions.
  • Prompts and tracebacks with color enabled by default <using-on-controlling-color>{.interpreted-text role="ref"}.
  • Interactive help browsing using F1{.interpreted-text role="kbd"} with a separate command history.
  • History browsing using F2{.interpreted-text role="kbd"} that skips output as well as the >>>{.interpreted-text role="term"} and ...{.interpreted-text role="term"} prompts.
  • "Paste mode" with F3{.interpreted-text role="kbd"} that makes pasting larger blocks of code easier (press F3{.interpreted-text role="kbd"} again to return to the regular prompt).

To disable the new interactive shell, set the PYTHON_BASIC_REPL{.interpreted-text role="envvar"} environment variable. For more on interactive mode, see tut-interac{.interpreted-text role="ref"}.

(Contributed by Pablo Galindo Salgado, Łukasz Langa, and Lysandros Nikolaou in 111201{.interpreted-text role="gh"} based on code from the PyPy project. Windows support contributed by Dino Viehland and Anthony Shaw.)

Improved error messages {#whatsnew313-improved-error-messages}

  • The interpreter now uses color by default when displaying tracebacks in the terminal. This feature can be controlled <using-on-controlling-color>{.interpreted-text role="ref"} via the new PYTHON_COLORS{.interpreted-text role="envvar"} environment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. (Contributed by Pablo Galindo Salgado in 112730{.interpreted-text role="gh"}.)

  • A common mistake is to write a script with the same name as a standard library module. When this results in errors, we now display a more helpful error message:

    $ python random.py
    Traceback (most recent call last):
      File "/home/me/random.py", line 1, in <module>
        import random
      File "/home/me/random.py", line 3, in <module>
        print(random.randint(5))
              ^^^^^^^^^^^^^^
    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)
    

    Similarly, if a script has the same name as a third-party module that it attempts to import and this results in errors, we also display a more helpful error message:

    $ python numpy.py
    Traceback (most recent call last):
      File "/home/me/numpy.py", line 1, in <module>
        import numpy as np
      File "/home/me/numpy.py", line 3, in <module>
        np.array([1, 2, 3])
        ^^^^^^^^
    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)
    

    (Contributed by Shantanu Jain in 95754{.interpreted-text role="gh"}.)

  • The error message now tries to suggest the correct keyword argument when an incorrect keyword argument is passed to a function.

    >>> "Better error messages!".split(max_split=1)
    Traceback (most recent call last):
      File "<python-input-0>", line 1, in <module>
        "Better error messages!".split(max_split=1)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
    TypeError: split() got an unexpected keyword argument 'max_split'. Did you mean 'maxsplit'?
    

    (Contributed by Pablo Galindo Salgado and Shantanu Jain in 107944{.interpreted-text role="gh"}.)

Free-threaded CPython {#whatsnew313-free-threaded-cpython}

CPython now has experimental support for running in a free-threaded mode, with the global interpreter lock{.interpreted-text role="term"} (GIL) disabled. This is an experimental feature and therefore is not enabled by default. The free-threaded mode requires a different executable, usually called python3.13t or python3.13t.exe. Pre-built binaries marked as free-threaded can be installed as part of the official Windows <install-freethreaded-windows>{.interpreted-text role="ref"} and macOS <install-freethreaded-macos>{.interpreted-text role="ref"} installers, or CPython can be built from source with the --disable-gil{.interpreted-text role="option"} option.

Free-threaded execution allows for full utilization of the available processing power by running threads in parallel on available CPU cores. While not all software will benefit from this automatically, programs designed with threading in mind will run faster on multi-core hardware. The free-threaded mode is experimental and work is ongoing to improve it: expect some bugs and a substantial single-threaded performance hit. Free-threaded builds of CPython support optionally running with the GIL enabled at runtime using the environment variable PYTHON_GIL{.interpreted-text role="envvar"} or the command-line option -X gil=1{.interpreted-text role="option"}.

To check if the current interpreter supports free-threading, python -VV <-V>{.interpreted-text role="option"} and sys.version{.interpreted-text role="data"} contain "experimental free-threading build". The new !sys._is_gil_enabled{.interpreted-text role="func"} function can be used to check whether the GIL is actually disabled in the running process.

C-API extension modules need to be built specifically for the free-threaded build. Extensions that support running with the GIL{.interpreted-text role="term"} disabled should use the Py_mod_gil{.interpreted-text role="c:data"} slot. Extensions using single-phase init should use PyUnstable_Module_SetGIL{.interpreted-text role="c:func"} to indicate whether they support running with the GIL disabled. Importing C extensions that don't use these mechanisms will cause the GIL to be enabled, unless the GIL was explicitly disabled with the PYTHON_GIL{.interpreted-text role="envvar"} environment variable or the -X gil=0{.interpreted-text role="option"} option. pip 24.1 or newer is required to install packages with C extensions in the free-threaded build.

This work was made possible thanks to many individuals and organizations, including the large community of contributors to Python and third-party projects to test and enable free-threading support. Notable contributors include: Sam Gross, Ken Jin, Donghee Na, Itamar Oren, Matt Page, Brett Simmers, Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, and many others. Many of these contributors are employed by Meta, which has provided significant engineering resources to support this project.

::: seealso 703{.interpreted-text role="pep"} "Making the Global Interpreter Lock Optional in CPython" contains rationale and information surrounding this work.

Porting Extension Modules to Support Free-Threading: A community-maintained porting guide for extension authors. :::

An experimental just-in-time (JIT) compiler {#whatsnew313-jit-compiler}

When CPython is configured and built using the !--enable-experimental-jit{.interpreted-text role="option"} option, a just-in-time (JIT) compiler is added which may speed up some Python programs. On Windows, use PCbuild/build.bat --experimental-jit to enable the JIT or --experimental-jit-interpreter to enable the Tier 2 interpreter. Build requirements and further supporting information are contained at Tools/jit/README.md{.interpreted-text role="file"}.

The !--enable-experimental-jit{.interpreted-text role="option"} option takes these (optional) values, defaulting to yes if !--enable-experimental-jit{.interpreted-text role="option"} is present without the optional value.

  • no: Disable the entire Tier 2 and JIT pipeline.
  • yes: Enable the JIT. To disable the JIT at runtime, pass the environment variable PYTHON_JIT=0.
  • yes-off: Build the JIT but disable it by default. To enable the JIT at runtime, pass the environment variable PYTHON_JIT=1.
  • interpreter: Enable the Tier 2 interpreter but disable the JIT. The interpreter can be disabled by running with PYTHON_JIT=0.

The internal architecture is roughly as follows:

  • We start with specialized Tier 1 bytecode. See What's new in 3.11 <whatsnew311-pep659>{.interpreted-text role="ref"} for details.
  • When the Tier 1 bytecode gets hot enough, it gets translated to a new purely internal intermediate representation (IR), called the Tier 2 IR, and sometimes referred to as micro-ops ("uops").
  • The Tier 2 IR uses the same stack-based virtual machine as Tier 1, but the instruction format is better suited to translation to machine code.
  • We have several optimization passes for Tier 2 IR, which are applied before it is interpreted or translated to machine code.
  • There is a Tier 2 interpreter, but it is mostly intended for debugging the earlier stages of the optimization pipeline. The Tier 2 interpreter can be enabled by configuring Python with --enable-experimental-jit=interpreter.
  • When the JIT is enabled, the optimized Tier 2 IR is translated to machine code, which is then executed.
  • The machine code translation process uses a technique called copy-and-patch. It has no runtime dependencies, but there is a new build-time dependency on LLVM.

::: seealso 744{.interpreted-text role="pep"} :::

(JIT by Brandt Bucher, inspired by a paper by Haoran Xu and Fredrik Kjolstad. Tier 2 IR by Mark Shannon and Guido van Rossum. Tier 2 optimizer by Ken Jin.)

Defined mutation semantics for locals{.interpreted-text role="py:func"} {#whatsnew313-locals-semantics}

Historically, the expected result of mutating the return value of locals{.interpreted-text role="func"} has been left to individual Python implementations to define. Starting from Python 3.13, 667{.interpreted-text role="pep"} standardises the historical behavior of CPython for most code execution scopes, but changes optimized scopes <optimized scope>{.interpreted-text role="term"} (functions, generators, coroutines, comprehensions, and generator expressions) to explicitly return independent snapshots of the currently assigned local variables, including locally referenced nonlocal variables captured in closures.

This change to the semantics of locals{.interpreted-text role="func"} in optimized scopes also affects the default behavior of code execution functions that implicitly target !locals{.interpreted-text role="func"} if no explicit namespace is provided (such as exec{.interpreted-text role="func"} and eval{.interpreted-text role="func"}). In previous versions, whether or not changes could be accessed by calling !locals{.interpreted-text role="func"} after calling the code execution function was implementation-dependent. In CPython specifically, such code would typically appear to work as desired, but could sometimes fail in optimized scopes based on other code (including debuggers and code execution tracing tools) potentially resetting the shared snapshot in that scope. Now, the code will always run against an independent snapshot of the local variables in optimized scopes, and hence the changes will never be visible in subsequent calls to !locals{.interpreted-text role="func"}. To access the changes made in these cases, an explicit namespace reference must now be passed to the relevant function. Alternatively, it may make sense to update affected code to use a higher level code execution API that returns the resulting code execution namespace (e.g. runpy.run_path{.interpreted-text role="func"} when executing Python files from disk).

To ensure debuggers and similar tools can reliably update local variables in scopes affected by this change, FrameType.f_locals <frame.f_locals>{.interpreted-text role="attr"} now returns a write-through proxy to the frame's local and locally referenced nonlocal variables in these scopes, rather than returning an inconsistently updated shared dict instance with undefined runtime semantics.

See 667{.interpreted-text role="pep"} for more details, including related C API changes and deprecations. Porting notes are also provided below for the affected Python APIs <pep667-porting-notes-py>{.interpreted-text role="ref"} and C APIs <pep667-porting-notes-c>{.interpreted-text role="ref"}.

(PEP and implementation contributed by Mark Shannon and Tian Gao in 74929{.interpreted-text role="gh"}. Documentation updates provided by Guido van Rossum and Alyssa Coghlan.)

Support for mobile platforms {#whatsnew313-platform-support}

730{.interpreted-text role="pep"}: iOS is now a 11{.interpreted-text role="pep"} supported platform, with the arm64-apple-ios and arm64-apple-ios-simulator targets at tier 3 (iPhone and iPad devices released after 2013 and the Xcode iOS simulator running on Apple silicon hardware, respectively). x86_64-apple-ios-simulator (the Xcode iOS simulator running on older x86_64 hardware) is not a tier 3 supported platform, but will have best-effort support. (PEP written and implementation contributed by Russell Keith-Magee in 114099{.interpreted-text role="gh"}.)

738{.interpreted-text role="pep"}: Android is now a 11{.interpreted-text role="pep"} supported platform, with the aarch64-linux-android and x86_64-linux-android targets at tier 3. The 32-bit targets arm-linux-androideabi and i686-linux-android are not tier 3 supported platforms, but will have best-effort support. (PEP written and implementation contributed by Malcolm Smith in 116622{.interpreted-text role="gh"}.)

::: seealso 730{.interpreted-text role="pep"}, 738{.interpreted-text role="pep"} :::

Other Language Changes

  • The compiler now strips common leading whitespace from every line in a docstring. This reduces the size of the bytecode cache <bytecode>{.interpreted-text role="term"} (such as .pyc files), with reductions in file size of around 5%, for example in !sqlalchemy.orm.session{.interpreted-text role="mod"} from SQLAlchemy 2.0. This change affects tools that use docstrings, such as doctest{.interpreted-text role="mod"}.

    ::: doctest >>> def spam(): ... """ ... This is a docstring with ... leading whitespace. ... ... It even has multiple paragraphs! ... """ ... >>> spam.__doc__ 'nThis is a docstring withn leading whitespace.nnIt even has multiple paragraphs!n' :::

    (Contributed by Inada Naoki in 81283{.interpreted-text role="gh"}.)

  • Annotation scopes <annotation-scopes>{.interpreted-text role="ref"} within class scopes can now contain lambdas and comprehensions. Comprehensions that are located within class scopes are not inlined into their parent scope.

    class C[T]:
        type Alias = lambda: T
    

    (Contributed by Jelle Zijlstra in 109118{.interpreted-text role="gh"} and 118160{.interpreted-text role="gh"}.)

  • Future statements <future>{.interpreted-text role="ref"} are no longer triggered by relative imports of the __future__{.interpreted-text role="mod"} module, meaning that statements of the form from .__future__ import ... are now simply standard relative imports, with no special features activated. (Contributed by Jeremiah Gabriel Pascual in 118216{.interpreted-text role="gh"}.)

  • global{.interpreted-text role="keyword"} declarations are now permitted in except{.interpreted-text role="keyword"} blocks when that global is used in the else{.interpreted-text role="keyword"} block. Previously this raised an erroneous SyntaxError{.interpreted-text role="exc"}. (Contributed by Irit Katriel in 111123{.interpreted-text role="gh"}.)

  • Add PYTHON_FROZEN_MODULES{.interpreted-text role="envvar"}, a new environment variable that determines whether frozen modules are ignored by the import machinery, equivalent to the -X frozen_modules <-X>{.interpreted-text role="option"} command-line option. (Contributed by Yilei Yang in 111374{.interpreted-text role="gh"}.)

  • Add support for the perf profiler <perf_profiling>{.interpreted-text role="ref"} working without frame pointers through the new environment variable PYTHON_PERF_JIT_SUPPORT{.interpreted-text role="envvar"} and command-line option -X perf_jit <-X>{.interpreted-text role="option"}. (Contributed by Pablo Galindo in 118518{.interpreted-text role="gh"}.)

  • The location of a .python_history{.interpreted-text role="file"} file can be changed via the new PYTHON_HISTORY{.interpreted-text role="envvar"} environment variable. (Contributed by Levi Sabah, Zackery Spytz and Hugo van Kemenade in 73965{.interpreted-text role="gh"}.)

  • Classes have a new ~type.__static_attributes__{.interpreted-text role="attr"} attribute. This is populated by the compiler with a tuple of the class's attribute names which are assigned through self.<name> from any function in its body. (Contributed by Irit Katriel in 115775{.interpreted-text role="gh"}.)

  • The compiler now creates a !__firstlineno__{.interpreted-text role="attr"} attribute on classes with the line number of the first line of the class definition. (Contributed by Serhiy Storchaka in 118465{.interpreted-text role="gh"}.)

  • The exec{.interpreted-text role="func"} and eval{.interpreted-text role="func"} builtins now accept the globals and locals arguments as keywords. (Contributed by Raphael Gaschignard in 105879{.interpreted-text role="gh"})

  • The compile{.interpreted-text role="func"} builtin now accepts a new flag, ast.PyCF_OPTIMIZED_AST, which is similar to ast.PyCF_ONLY_AST except that the returned AST is optimized according to the value of the optimize argument. (Contributed by Irit Katriel in 108113{.interpreted-text role="gh"}).

  • Add a ~property.__name__{.interpreted-text role="attr"} attribute on property{.interpreted-text role="class"} objects. (Contributed by Eugene Toder in 101860{.interpreted-text role="gh"}.)

  • Add PythonFinalizationError{.interpreted-text role="exc"}, a new exception derived from RuntimeError{.interpreted-text role="exc"} and used to signal when operations are blocked during finalization <interpreter shutdown>{.interpreted-text role="term"}. The following callables now raise !PythonFinalizationError{.interpreted-text role="exc"}, instead of RuntimeError{.interpreted-text role="exc"}:

    • _thread.start_new_thread{.interpreted-text role="func"}
    • os.fork{.interpreted-text role="func"}
    • os.forkpty{.interpreted-text role="func"}
    • subprocess.Popen{.interpreted-text role="class"}

    (Contributed by Victor Stinner in 114570{.interpreted-text role="gh"}.)

  • Allow the count argument of str.replace{.interpreted-text role="meth"} to be a keyword. (Contributed by Hugo van Kemenade in 106487{.interpreted-text role="gh"}.)

  • Many functions now emit a warning if a boolean value is passed as a file descriptor argument. This can help catch some errors earlier. (Contributed by Serhiy Storchaka in 82626{.interpreted-text role="gh"}.)

  • Added !name{.interpreted-text role="attr"} and !mode{.interpreted-text role="attr"} attributes for compressed and archived file-like objects in the bz2{.interpreted-text role="mod"}, lzma{.interpreted-text role="mod"}, tarfile{.interpreted-text role="mod"}, and zipfile{.interpreted-text role="mod"} modules. (Contributed by Serhiy Storchaka in 115961{.interpreted-text role="gh"}.)

New Modules

  • dbm.sqlite3{.interpreted-text role="mod"}: An SQLite backend for dbm{.interpreted-text role="mod"}. (Contributed by Raymond Hettinger and Erlend E. Aasland in 100414{.interpreted-text role="gh"}.)

Improved Modules

argparse

  • Add the deprecated parameter to the ~argparse.ArgumentParser.add_argument{.interpreted-text role="meth"} and !add_parser{.interpreted-text role="meth"} methods, to enable deprecating command-line options, positional arguments, and subcommands. (Contributed by Serhiy Storchaka in 83648{.interpreted-text role="gh"}.)

array

  • Add the 'w' type code (Py_UCS4) for Unicode characters. It should be used instead of the deprecated 'u' type code. (Contributed by Inada Naoki in 80480{.interpreted-text role="gh"}.)
  • Register array.array{.interpreted-text role="class"} as a ~collections.abc.MutableSequence{.interpreted-text role="class"} by implementing the ~array.array.clear{.interpreted-text role="meth"} method. (Contributed by Mike Zimin in 114894{.interpreted-text role="gh"}.)

ast

  • The constructors of node types in the ast{.interpreted-text role="mod"} module are now stricter in the arguments they accept, with more intuitive behavior when arguments are omitted.

    If an optional field on an AST node is not included as an argument when constructing an instance, the field will now be set to None. Similarly, if a list field is omitted, that field will now be set to an empty list, and if an !expr_context{.interpreted-text role="class"} field is omitted, it defaults to Load() <ast.Load>{.interpreted-text role="class"}. (Previously, in all cases, the attribute would be missing on the newly constructed AST node instance.)

    In all other cases, where a required argument is omitted, the node constructor will emit a DeprecationWarning{.interpreted-text role="exc"}. This will raise an exception in Python 3.15. Similarly, passing a keyword argument to the constructor that does not map to a field on the AST node is now deprecated, and will raise an exception in Python 3.15.

    These changes do not apply to user-defined subclasses of ast.AST{.interpreted-text role="class"} unless the class opts in to the new behavior by defining the .AST._field_types{.interpreted-text role="attr"} mapping.

    (Contributed by Jelle Zijlstra in 105858{.interpreted-text role="gh"}, 117486{.interpreted-text role="gh"}, and 118851{.interpreted-text role="gh"}.)

  • ast.parse{.interpreted-text role="func"} now accepts an optional argument optimize which is passed on to compile{.interpreted-text role="func"}. This makes it possible to obtain an optimized AST. (Contributed by Irit Katriel in 108113{.interpreted-text role="gh"}.)

asyncio

  • asyncio.as_completed{.interpreted-text role="func"} now returns an object that is both an asynchronous iterator{.interpreted-text role="term"} and a plain iterator{.interpreted-text role="term"} of awaitables <awaitable>{.interpreted-text role="term"}. The awaitables yielded by asynchronous iteration include original task or future objects that were passed in, making it easier to associate results with the tasks being completed. (Contributed by Justin Arthur in 77714{.interpreted-text role="gh"}.)

  • asyncio.loop.create_unix_server{.interpreted-text role="meth"} will now automatically remove the Unix socket when the server is closed. (Contributed by Pierre Ossman in 111246{.interpreted-text role="gh"}.)

  • .DatagramTransport.sendto{.interpreted-text role="meth"} will now send zero-length datagrams if called with an empty bytes object. The transport flow control also now accounts for the datagram header when calculating the buffer size. (Contributed by Jamie Phan in 115199{.interpreted-text role="gh"}.)

  • Add Queue.shutdown <asyncio.Queue.shutdown>{.interpreted-text role="meth"} and ~asyncio.QueueShutDown{.interpreted-text role="exc"} to manage queue termination. (Contributed by Laurie Opperman and Yves Duprat in 104228{.interpreted-text role="gh"}.)

  • Add the .Server.close_clients{.interpreted-text role="meth"} and .Server.abort_clients{.interpreted-text role="meth"} methods, which more forcefully close an asyncio server. (Contributed by Pierre Ossman in 113538{.interpreted-text role="gh"}.)

  • Accept a tuple of separators in .StreamReader.readuntil{.interpreted-text role="meth"}, stopping when any one of them is encountered. (Contributed by Bruce Merry in 81322{.interpreted-text role="gh"}.)

  • Improve the behavior of ~asyncio.TaskGroup{.interpreted-text role="class"} when an external cancellation collides with an internal cancellation. For example, when two task groups are nested and both experience an exception in a child task simultaneously, it was possible that the outer task group would hang, because its internal cancellation was swallowed by the inner task group.

    In the case where a task group is cancelled externally and also must raise an ExceptionGroup{.interpreted-text role="exc"}, it will now call the parent task's ~asyncio.Task.cancel{.interpreted-text role="meth"} method. This ensures that a ~asyncio.CancelledError{.interpreted-text role="exc"} will be raised at the next await{.interpreted-text role="keyword"}, so the cancellation is not lost.

    An added benefit of these changes is that task groups now preserve the cancellation count (~asyncio.Task.cancelling{.interpreted-text role="meth"}).

    In order to handle some corner cases, ~asyncio.Task.uncancel{.interpreted-text role="meth"} may now reset the undocumented _must_cancel flag when the cancellation count reaches zero.

    (Inspired by an issue reported by Arthur Tacca in 116720{.interpreted-text role="gh"}.)

  • When .TaskGroup.create_task{.interpreted-text role="meth"} is called on an inactive ~asyncio.TaskGroup{.interpreted-text role="class"}, the given coroutine will be closed (which prevents a RuntimeWarning{.interpreted-text role="exc"} about the given coroutine being never awaited). (Contributed by Arthur Tacca and Jason Zhang in 115957{.interpreted-text role="gh"}.)

  • The function and methods named create_task have received a new **kwargs argument that is passed through to the task constructor. This change was accidentally added in 3.13.3, and broke the API contract for custom task factories. Several third-party task factories implemented workarounds for this. In 3.13.4 and later releases the old factory contract is honored once again (until 3.14). To keep the workarounds working, the extra **kwargs argument still allows passing additional keyword arguments to ~asyncio.Task{.interpreted-text role="class"} and to custom task factories.

    This affects the following function and methods: asyncio.create_task{.interpreted-text role="meth"}, asyncio.loop.create_task{.interpreted-text role="meth"}, asyncio.TaskGroup.create_task{.interpreted-text role="meth"}. (Contributed by Thomas Grainger in 128307{.interpreted-text role="gh"}.)

base64

  • Add ~base64.z85encode{.interpreted-text role="func"} and ~base64.z85decode{.interpreted-text role="func"} functions for encoding bytes{.interpreted-text role="class"} as Z85 data and decoding Z85-encoded data to !bytes{.interpreted-text role="class"}. (Contributed by Matan Perelman in 75299{.interpreted-text role="gh"}.)

compileall

  • The default number of worker threads and processes is now selected using os.process_cpu_count{.interpreted-text role="func"} instead of os.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in 109649{.interpreted-text role="gh"}.)

concurrent.futures

  • The default number of worker threads and processes is now selected using os.process_cpu_count{.interpreted-text role="func"} instead of os.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in 109649{.interpreted-text role="gh"}.)

configparser

  • ~configparser.ConfigParser{.interpreted-text role="class"} now has support for unnamed sections, which allows for top-level key-value pairs. This can be enabled with the new allow_unnamed_section parameter. (Contributed by Pedro Sousa Lacerda in 66449{.interpreted-text role="gh"}.)

copy

  • The new ~copy.replace{.interpreted-text role="func"} function and the replace protocol <object.__replace__>{.interpreted-text role="meth"} make creating modified copies of objects much simpler. This is especially useful when working with immutable objects. The following types support the ~copy.replace{.interpreted-text role="func"} function and implement the replace protocol:

    • collections.namedtuple{.interpreted-text role="func"}
    • dataclasses.dataclass{.interpreted-text role="class"}
    • datetime.datetime{.interpreted-text role="class"}, datetime.date{.interpreted-text role="class"}, datetime.time{.interpreted-text role="class"}
    • inspect.Signature{.interpreted-text role="class"}, inspect.Parameter{.interpreted-text role="class"}
    • types.SimpleNamespace{.interpreted-text role="class"}
    • code objects <code-objects>{.interpreted-text role="ref"}

    Any user-defined class can also support copy.replace{.interpreted-text role="func"} by defining the ~object.__replace__{.interpreted-text role="meth"} method. (Contributed by Serhiy Storchaka in 108751{.interpreted-text role="gh"}.)

ctypes

  • As a consequence of necessary internal refactoring, initialization of internal metaclasses now happens in __init__ rather than in __new__. This affects projects that subclass these internal metaclasses to provide custom initialization. Generally:

    • Custom logic that was done in __new__ after calling super().__new__ should be moved to __init__.
    • To create a class, call the metaclass, not only the metaclass's __new__ method.

    See 124520{.interpreted-text role="gh"} for discussion and links to changes in some affected projects.

  • ctypes.Structure{.interpreted-text role="class"} objects have a new ~ctypes.Structure._align_{.interpreted-text role="attr"} attribute which allows the alignment of the structure being packed to/from memory to be specified explicitly. (Contributed by Matt Sanderson in 112433{.interpreted-text role="gh"})

dbm

  • Add dbm.sqlite3{.interpreted-text role="mod"}, a new module which implements an SQLite backend, and make it the default !dbm{.interpreted-text role="mod"} backend. (Contributed by Raymond Hettinger and Erlend E. Aasland in 100414{.interpreted-text role="gh"}.)
  • Allow removing all items from the database through the new !clear{.interpreted-text role="meth"} methods of the GDBM and NDBM database objects. (Contributed by Donghee Na in 107122{.interpreted-text role="gh"}.)

dis

  • Change the output of dis{.interpreted-text role="mod"} module functions to show logical labels for jump targets and exception handlers, rather than offsets. The offsets can be added with the new -O <dis --show-offsets>{.interpreted-text role="option"} command-line option or the show_offsets argument. (Contributed by Irit Katriel in 112137{.interpreted-text role="gh"}.)
  • ~dis.get_instructions{.interpreted-text role="meth"} no longer represents cache entries as separate instructions. Instead, it returns them as part of the ~dis.Instruction{.interpreted-text role="class"}, in the new cache_info field. The show_caches argument to ~dis.get_instructions{.interpreted-text role="meth"} is deprecated and no longer has any effect. (Contributed by Irit Katriel in 112962{.interpreted-text role="gh"}.)

doctest {#whatsnew313-doctest}

  • doctest{.interpreted-text role="mod"} output is now colored by default. This can be controlled via the new PYTHON_COLORS{.interpreted-text role="envvar"} environment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. See also using-on-controlling-color{.interpreted-text role="ref"}. (Contributed by Hugo van Kemenade in 117225{.interpreted-text role="gh"}.)
  • The .DocTestRunner.run{.interpreted-text role="meth"} method now counts the number of skipped tests. Add the .DocTestRunner.skips{.interpreted-text role="attr"} and .TestResults.skipped{.interpreted-text role="attr"} attributes. (Contributed by Victor Stinner in 108794{.interpreted-text role="gh"}.)

email

  • Headers with embedded newlines are now quoted on output. The ~email.generator{.interpreted-text role="mod"} will now refuse to serialize (write) headers that are improperly folded or delimited, such that they would be parsed as multiple headers or joined with adjacent data. If you need to turn this safety feature off, set ~email.policy.Policy.verify_generated_headers{.interpreted-text role="attr"}. (Contributed by Bas Bloemsaat and Petr Viktorin in 121650{.interpreted-text role="gh"}.)
  • ~email.utils.getaddresses{.interpreted-text role="func"} and ~email.utils.parseaddr{.interpreted-text role="func"} now return ('', '') pairs in more situations where invalid email addresses are encountered instead of potentially inaccurate values. The two functions have a new optional strict parameter (default True). To get the old behavior (accepting malformed input), use strict=False. getattr(email.utils, 'supports_strict_parsing', False) can be used to check if the strict parameter is available. (Contributed by Thomas Dwyer and Victor Stinner for 102988{.interpreted-text role="gh"} to improve the 2023-27043{.interpreted-text role="cve"} fix.)

enum

  • ~enum.EnumDict{.interpreted-text role="class"} has been made public to better support subclassing ~enum.EnumType{.interpreted-text role="class"}.

fractions

  • ~fractions.Fraction{.interpreted-text role="class"} objects now support the standard format specification mini-language <formatspec>{.interpreted-text role="ref"} rules for fill, alignment, sign handling, minimum width, and grouping. (Contributed by Mark Dickinson in 111320{.interpreted-text role="gh"}.)

glob

  • Add ~glob.translate{.interpreted-text role="func"}, a function to convert a path specification with shell-style wildcards to a regular expression. (Contributed by Barney Gale in 72904{.interpreted-text role="gh"}.)

importlib

  • The following functions in importlib.resources{.interpreted-text role="mod"} now allow accessing a directory (or tree) of resources, using multiple positional arguments (the encoding and errors arguments in the text-reading functions are now keyword-only):

    • ~importlib.resources.is_resource{.interpreted-text role="func"}
    • ~importlib.resources.open_binary{.interpreted-text role="func"}
    • ~importlib.resources.open_text{.interpreted-text role="func"}
    • ~importlib.resources.path{.interpreted-text role="func"}
    • ~importlib.resources.read_binary{.interpreted-text role="func"}
    • ~importlib.resources.read_text{.interpreted-text role="func"}

    These functions are no longer deprecated and are not scheduled for removal. (Contributed by Petr Viktorin in 116608{.interpreted-text role="gh"}.)

  • ~importlib.resources.contents{.interpreted-text role="func"} remains deprecated in favor of the fully-featured ~importlib.resources.abc.Traversable{.interpreted-text role="class"} API. However, there is now no plan to remove it. (Contributed by Petr Viktorin in 116608{.interpreted-text role="gh"}.)

io

  • The ~io.IOBase{.interpreted-text role="class"} finalizer now logs any errors raised by the ~io.IOBase.close{.interpreted-text role="meth"} method with sys.unraisablehook{.interpreted-text role="data"}. Previously, errors were ignored silently by default, and only logged in Python Development Mode <devmode>{.interpreted-text role="ref"} or when using a Python debug build <debug-build>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in 62948{.interpreted-text role="gh"}.)

ipaddress

  • Add the .IPv4Address.ipv6_mapped{.interpreted-text role="attr"} property, which returns the IPv4-mapped IPv6 address. (Contributed by Charles Machalow in 109466{.interpreted-text role="gh"}.)
  • Fix is_global and is_private behavior in ~ipaddress.IPv4Address{.interpreted-text role="class"}, ~ipaddress.IPv6Address{.interpreted-text role="class"}, ~ipaddress.IPv4Network{.interpreted-text role="class"}, and ~ipaddress.IPv6Network{.interpreted-text role="class"}. (Contributed by Jakub Stasiak in 113171{.interpreted-text role="gh"}.)

itertools

  • ~itertools.batched{.interpreted-text role="func"} has a new strict parameter, which raises a ValueError{.interpreted-text role="exc"} if the final batch is shorter than the specified batch size. (Contributed by Raymond Hettinger in 113202{.interpreted-text role="gh"}.)

marshal

  • Add the allow_code parameter in module functions. Passing allow_code=False prevents serialization and de-serialization of code objects which are incompatible between Python versions. (Contributed by Serhiy Storchaka in 113626{.interpreted-text role="gh"}.)

math

  • The new function ~math.fma{.interpreted-text role="func"} performs fused multiply-add operations. This computes x * y + z with only a single round, and so avoids any intermediate loss of precision. It wraps the fma() function provided by C99, and follows the specification of the IEEE 754 "fusedMultiplyAdd" operation for special cases. (Contributed by Mark Dickinson and Victor Stinner in 73468{.interpreted-text role="gh"}.)

mimetypes

  • Add the ~mimetypes.guess_file_type{.interpreted-text role="func"} function to guess a MIME type from a filesystem path. Using paths with ~mimetypes.guess_type{.interpreted-text role="func"} is now soft deprecated{.interpreted-text role="term"}. (Contributed by Serhiy Storchaka in 66543{.interpreted-text role="gh"}.)

mmap

  • ~mmap.mmap{.interpreted-text role="class"} is now protected from crashing on Windows when the mapped memory is inaccessible due to file system errors or access violations. (Contributed by Jannis Weigend in 118209{.interpreted-text role="gh"}.)
  • ~mmap.mmap{.interpreted-text role="class"} has a new ~mmap.mmap.seekable{.interpreted-text role="meth"} method that can be used when a seekable file-like object is required. The ~mmap.mmap.seek{.interpreted-text role="meth"} method now returns the new absolute position. (Contributed by Donghee Na and Sylvie Liberman in 111835{.interpreted-text role="gh"}.)
  • The new UNIX-only trackfd parameter for ~mmap.mmap{.interpreted-text role="class"} controls file descriptor duplication; if false, the file descriptor specified by fileno will not be duplicated. (Contributed by Zackery Spytz and Petr Viktorin in 78502{.interpreted-text role="gh"}.)

multiprocessing

  • The default number of worker threads and processes is now selected using os.process_cpu_count{.interpreted-text role="func"} instead of os.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in 109649{.interpreted-text role="gh"}.)

os

  • Add ~os.process_cpu_count{.interpreted-text role="func"} function to get the number of logical CPU cores usable by the calling thread of the current process. (Contributed by Victor Stinner in 109649{.interpreted-text role="gh"}.)
  • ~os.cpu_count{.interpreted-text role="func"} and ~os.process_cpu_count{.interpreted-text role="func"} can be overridden through the new environment variable PYTHON_CPU_COUNT{.interpreted-text role="envvar"} or the new command-line option -X cpu_count <-X>{.interpreted-text role="option"}. This option is useful for users who need to limit CPU resources of a container system without having to modify application code or the container itself. (Contributed by Donghee Na in 109595{.interpreted-text role="gh"}.)
  • Add a low level interface <os-timerfd>{.interpreted-text role="ref"} to Linux's timer file descriptors <timerfd_create(2)>{.interpreted-text role="manpage"} via ~os.timerfd_create{.interpreted-text role="func"}, ~os.timerfd_settime{.interpreted-text role="func"}, ~os.timerfd_settime_ns{.interpreted-text role="func"}, ~os.timerfd_gettime{.interpreted-text role="func"}, ~os.timerfd_gettime_ns{.interpreted-text role="func"}, ~os.TFD_NONBLOCK{.interpreted-text role="const"}, ~os.TFD_CLOEXEC{.interpreted-text role="const"}, ~os.TFD_TIMER_ABSTIME{.interpreted-text role="const"}, and ~os.TFD_TIMER_CANCEL_ON_SET{.interpreted-text role="const"} (Contributed by Masaru Tsuchiyama in 108277{.interpreted-text role="gh"}.)
  • ~os.lchmod{.interpreted-text role="func"} and the follow_symlinks argument of ~os.chmod{.interpreted-text role="func"} are both now available on Windows. Note that the default value of follow_symlinks in !lchmod{.interpreted-text role="func"} is False on Windows. (Contributed by Serhiy Storchaka in 59616{.interpreted-text role="gh"}.)
  • ~os.fchmod{.interpreted-text role="func"} and support for file descriptors in ~os.chmod{.interpreted-text role="func"} are both now available on Windows. (Contributed by Serhiy Storchaka in 113191{.interpreted-text role="gh"}.)
  • On Windows, ~os.mkdir{.interpreted-text role="func"} and ~os.makedirs{.interpreted-text role="func"} now support passing a mode value of 0o700 to apply access control to the new directory. This implicitly affects tempfile.mkdtemp{.interpreted-text role="func"} and is a mitigation for 2024-4030{.interpreted-text role="cve"}. Other values for mode continue to be ignored. (Contributed by Steve Dower in 118486{.interpreted-text role="gh"}.)
  • ~os.posix_spawn{.interpreted-text role="func"} now accepts None for the env argument, which makes the newly spawned process use the current process environment. (Contributed by Jakub Kulik in 113119{.interpreted-text role="gh"}.)
  • ~os.posix_spawn{.interpreted-text role="func"} can now use the ~os.POSIX_SPAWN_CLOSEFROM{.interpreted-text role="const"} attribute in the file_actions parameter on platforms that support !posix_spawn_file_actions_addclosefrom_np{.interpreted-text role="c:func"}. (Contributed by Jakub Kulik in 113117{.interpreted-text role="gh"}.)

os.path

  • Add ~os.path.isreserved{.interpreted-text role="func"} to check if a path is reserved on the current system. This function is only available on Windows. (Contributed by Barney Gale in 88569{.interpreted-text role="gh"}.)
  • On Windows, ~os.path.isabs{.interpreted-text role="func"} no longer considers paths starting with exactly one slash (\ or /) to be absolute. (Contributed by Barney Gale and Jon Foster in 44626{.interpreted-text role="gh"}.)
  • ~os.path.realpath{.interpreted-text role="func"} now resolves MS-DOS style file names even if the file is not accessible. (Contributed by Moonsik Park in 82367{.interpreted-text role="gh"}.)

pathlib

  • Add ~pathlib.UnsupportedOperation{.interpreted-text role="exc"}, which is raised instead of NotImplementedError{.interpreted-text role="exc"} when a path operation isn't supported. (Contributed by Barney Gale in 89812{.interpreted-text role="gh"}.)
  • Add a new constructor for creating ~pathlib.Path{.interpreted-text role="class"} objects from 'file' URIs (file:///), .Path.from_uri{.interpreted-text role="meth"}. (Contributed by Barney Gale in 107465{.interpreted-text role="gh"}.)
  • Add .PurePath.full_match{.interpreted-text role="meth"} for matching paths with shell-style wildcards, including the recursive wildcard "**". (Contributed by Barney Gale in 73435{.interpreted-text role="gh"}.)
  • Add the .PurePath.parser{.interpreted-text role="attr"} class attribute to store the implementation of os.path{.interpreted-text role="mod"} used for low-level path parsing and joining. This will be either !posixpath{.interpreted-text role="mod"} or !ntpath{.interpreted-text role="mod"}.
  • Add recurse_symlinks keyword-only argument to .Path.glob{.interpreted-text role="meth"} and ~pathlib.Path.rglob{.interpreted-text role="meth"}. (Contributed by Barney Gale in 77609{.interpreted-text role="gh"}.)
  • .Path.glob{.interpreted-text role="meth"} and ~pathlib.Path.rglob{.interpreted-text role="meth"} now return files and directories when given a pattern that ends with "**". Previously, only directories were returned. (Contributed by Barney Gale in 70303{.interpreted-text role="gh"}.)
  • Add the follow_symlinks keyword-only argument to Path.is_file <pathlib.Path.is_file>{.interpreted-text role="meth"}, Path.is_dir <pathlib.Path.is_dir>{.interpreted-text role="meth"}, .Path.owner{.interpreted-text role="meth"}, and .Path.group{.interpreted-text role="meth"}. (Contributed by Barney Gale in 105793{.interpreted-text role="gh"} and Kamil Turek in 107962{.interpreted-text role="gh"}.)

pdb

  • breakpoint{.interpreted-text role="func"} and ~pdb.set_trace{.interpreted-text role="func"} now enter the debugger immediately rather than on the next line of code to be executed. This change prevents the debugger from breaking outside of the context when !breakpoint{.interpreted-text role="func"} is positioned at the end of the context. (Contributed by Tian Gao in 118579{.interpreted-text role="gh"}.)
  • sys.path[0] is no longer replaced by the directory of the script being debugged when sys.flags.safe_path{.interpreted-text role="attr"} is set. (Contributed by Tian Gao and Christian Walther in 111762{.interpreted-text role="gh"}.)
  • zipapp{.interpreted-text role="mod"} is now supported as a debugging target. (Contributed by Tian Gao in 118501{.interpreted-text role="gh"}.)
  • Add ability to move between chained exceptions during post-mortem debugging in ~pdb.pm{.interpreted-text role="func"} using the new exceptions [exc_number] <exceptions>{.interpreted-text role="pdbcmd"} command for Pdb. (Contributed by Matthias Bussonnier in 106676{.interpreted-text role="gh"}.)
  • Expressions and statements whose prefix is a pdb command are now correctly identified and executed. (Contributed by Tian Gao in 108464{.interpreted-text role="gh"}.)

queue

  • Add Queue.shutdown <queue.Queue.shutdown>{.interpreted-text role="meth"} and ~queue.ShutDown{.interpreted-text role="exc"} to manage queue termination. (Contributed by Laurie Opperman and Yves Duprat in 104750{.interpreted-text role="gh"}.)

random

  • Add a command-line interface <random-cli>{.interpreted-text role="ref"}. (Contributed by Hugo van Kemenade in 118131{.interpreted-text role="gh"}.)

re

  • Rename !re.error{.interpreted-text role="exc"} to ~re.PatternError{.interpreted-text role="exc"} for improved clarity. !re.error{.interpreted-text role="exc"} is kept for backward compatibility.

shutil

  • Support the dir_fd and follow_symlinks keyword arguments in ~shutil.chown{.interpreted-text role="func"}. (Contributed by Berker Peksag and Tahia K in 62308{.interpreted-text role="gh"})

site

  • .pth{.interpreted-text role="file"} files are now decoded using UTF-8 first, and then with the locale encoding{.interpreted-text role="term"} if UTF-8 decoding fails. (Contributed by Inada Naoki in 117802{.interpreted-text role="gh"}.)

sqlite3

  • A ResourceWarning{.interpreted-text role="exc"} is now emitted if a ~sqlite3.Connection{.interpreted-text role="class"} object is not closed <sqlite3.Connection.close>{.interpreted-text role="meth"} explicitly. (Contributed by Erlend E. Aasland in 105539{.interpreted-text role="gh"}.)
  • Add the filter keyword-only parameter to .Connection.iterdump{.interpreted-text role="meth"} for filtering database objects to dump. (Contributed by Mariusz Felisiak in 91602{.interpreted-text role="gh"}.)

ssl

  • The ~ssl.create_default_context{.interpreted-text role="func"} API now includes ~ssl.VERIFY_X509_PARTIAL_CHAIN{.interpreted-text role="data"} and ~ssl.VERIFY_X509_STRICT{.interpreted-text role="data"} in its default flags.

    :::: note ::: title Note :::

    ~ssl.VERIFY_X509_STRICT{.interpreted-text role="data"} may reject pre-5280{.interpreted-text role="rfc"} or malformed certificates that the underlying OpenSSL implementation might otherwise accept. Whilst disabling this is not recommended, you can do so using:

    import ssl
    
    ctx = ssl.create_default_context()
    ctx.verify_flags &= ~ssl.VERIFY_X509_STRICT
    

    ::::

    (Contributed by William Woodruff in 112389{.interpreted-text role="gh"}.)

statistics

  • Add ~statistics.kde{.interpreted-text role="func"} for kernel density estimation. This makes it possible to estimate a continuous probability density function from a fixed number of discrete samples. (Contributed by Raymond Hettinger in 115863{.interpreted-text role="gh"}.)
  • Add ~statistics.kde_random{.interpreted-text role="func"} for sampling from an estimated probability density function created by ~statistics.kde{.interpreted-text role="func"}. (Contributed by Raymond Hettinger in 115863{.interpreted-text role="gh"}.)

subprocess {#whatsnew313-subprocess}

  • The subprocess{.interpreted-text role="mod"} module now uses the ~os.posix_spawn{.interpreted-text role="func"} function in more situations.

    Notably, when close_fds is True (the default), ~os.posix_spawn{.interpreted-text role="func"} will be used when the C library provides !posix_spawn_file_actions_addclosefrom_np{.interpreted-text role="c:func"}, which includes recent versions of Linux, FreeBSD, and Solaris. On Linux, this should perform similarly to the existing Linux !vfork{.interpreted-text role="c:func"} based code.

    A private control knob !subprocess._USE_POSIX_SPAWN{.interpreted-text role="attr"} can be set to False if you need to force subprocess{.interpreted-text role="mod"} to never use ~os.posix_spawn{.interpreted-text role="func"}. Please report your reason and platform details in the issue tracker <using-the-tracker>{.interpreted-text role="ref"} if you set this so that we can improve our API selection logic for everyone. (Contributed by Jakub Kulik in 113117{.interpreted-text role="gh"}.)

sys

  • Add the ~sys._is_interned{.interpreted-text role="func"} function to test if a string was interned. This function is not guaranteed to exist in all implementations of Python. (Contributed by Serhiy Storchaka in 78573{.interpreted-text role="gh"}.)

tempfile

  • On Windows, the default mode 0o700 used by tempfile.mkdtemp{.interpreted-text role="func"} now limits access to the new directory due to changes to os.mkdir{.interpreted-text role="func"}. This is a mitigation for 2024-4030{.interpreted-text role="cve"}. (Contributed by Steve Dower in 118486{.interpreted-text role="gh"}.)

time

  • On Windows, ~time.monotonic{.interpreted-text role="func"} now uses the QueryPerformanceCounter() clock for a resolution of 1 microsecond, instead of the GetTickCount64() clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in 88494{.interpreted-text role="gh"}.)
  • On Windows, ~time.time{.interpreted-text role="func"} now uses the GetSystemTimePreciseAsFileTime() clock for a resolution of 1 microsecond, instead of the GetSystemTimeAsFileTime() clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in 63207{.interpreted-text role="gh"}.)

tkinter

  • Add tkinter{.interpreted-text role="mod"} widget methods: !tk_busy_hold{.interpreted-text role="meth"}, !tk_busy_configure{.interpreted-text role="meth"}, !tk_busy_cget{.interpreted-text role="meth"}, !tk_busy_forget{.interpreted-text role="meth"}, !tk_busy_current{.interpreted-text role="meth"}, and !tk_busy_status{.interpreted-text role="meth"}. (Contributed by Miguel, klappnase and Serhiy Storchaka in 72684{.interpreted-text role="gh"}.)
  • The tkinter{.interpreted-text role="mod"} widget method !wm_attributes{.interpreted-text role="meth"} now accepts the attribute name without the minus prefix to get window attributes, for example w.wm_attributes('alpha') and allows specifying attributes and values to set as keyword arguments, for example w.wm_attributes(alpha=0.5). (Contributed by Serhiy Storchaka in 43457{.interpreted-text role="gh"}.)
  • !wm_attributes{.interpreted-text role="meth"} can now return attributes as a dict{.interpreted-text role="class"}, by using the new optional keyword-only parameter return_python_dict. (Contributed by Serhiy Storchaka in 43457{.interpreted-text role="gh"}.)
  • !Text.count{.interpreted-text role="meth"} can now return a simple int{.interpreted-text role="class"} when the new optional keyword-only parameter return_ints is used. Otherwise, the single count is returned as a 1-tuple or None. (Contributed by Serhiy Storchaka in 97928{.interpreted-text role="gh"}.)
  • Support the "vsapi" element type in the ~tkinter.ttk.Style.element_create{.interpreted-text role="meth"} method of tkinter.ttk.Style{.interpreted-text role="class"}. (Contributed by Serhiy Storchaka in 68166{.interpreted-text role="gh"}.)
  • Add the !after_info{.interpreted-text role="meth"} method for Tkinter widgets. (Contributed by Cheryl Sabella in 77020{.interpreted-text role="gh"}.)
  • Add a new !copy_replace{.interpreted-text role="meth"} method to !PhotoImage{.interpreted-text role="class"} to copy a region from one image to another, possibly with pixel zooming, subsampling, or both. (Contributed by Serhiy Storchaka in 118225{.interpreted-text role="gh"}.)
  • Add from_coords parameter to the !PhotoImage{.interpreted-text role="class"} methods !copy{.interpreted-text role="meth"}, !zoom{.interpreted-text role="meth"} and !subsample{.interpreted-text role="meth"}. Add zoom and subsample parameters to the !PhotoImage{.interpreted-text role="class"} method !copy{.interpreted-text role="meth"}. (Contributed by Serhiy Storchaka in 118225{.interpreted-text role="gh"}.)
  • Add the !PhotoImage{.interpreted-text role="class"} methods !read{.interpreted-text role="meth"} to read an image from a file and !data{.interpreted-text role="meth"} to get the image data. Add background and grayscale parameters to the !write{.interpreted-text role="meth"} method. (Contributed by Serhiy Storchaka in 118271{.interpreted-text role="gh"}.)

traceback

  • Add the ~traceback.TracebackException.exc_type_str{.interpreted-text role="attr"} attribute to ~traceback.TracebackException{.interpreted-text role="class"}, which holds a string display of the exc_type. Deprecate the ~traceback.TracebackException.exc_type{.interpreted-text role="attr"} attribute, which holds the type object itself. Add parameter save_exc_type (default True) to indicate whether exc_type should be saved. (Contributed by Irit Katriel in 112332{.interpreted-text role="gh"}.)
  • Add a new show_group keyword-only parameter to .TracebackException.format_exception_only{.interpreted-text role="meth"} to (recursively) format the nested exceptions of a BaseExceptionGroup{.interpreted-text role="exc"} instance. (Contributed by Irit Katriel in 105292{.interpreted-text role="gh"}.)

types

  • ~types.SimpleNamespace{.interpreted-text role="class"} can now take a single positional argument to initialise the namespace's arguments. This argument must either be a mapping or an iterable of key-value pairs. (Contributed by Serhiy Storchaka in 108191{.interpreted-text role="gh"}.)

typing

  • 705{.interpreted-text role="pep"}: Add ~typing.ReadOnly{.interpreted-text role="data"}, a special typing construct to mark a ~typing.TypedDict{.interpreted-text role="class"} item as read-only for type checkers.
  • 742{.interpreted-text role="pep"}: Add ~typing.TypeIs{.interpreted-text role="data"}, a typing construct that can be used to instruct a type checker how to narrow a type.
  • Add ~typing.NoDefault{.interpreted-text role="data"}, a sentinel object used to represent the defaults of some parameters in the typing{.interpreted-text role="mod"} module. (Contributed by Jelle Zijlstra in 116126{.interpreted-text role="gh"}.)
  • Add ~typing.get_protocol_members{.interpreted-text role="func"} to return the set of members defining a typing.Protocol{.interpreted-text role="class"}. (Contributed by Jelle Zijlstra in 104873{.interpreted-text role="gh"}.)
  • Add ~typing.is_protocol{.interpreted-text role="func"} to check whether a class is a ~typing.Protocol{.interpreted-text role="class"}. (Contributed by Jelle Zijlstra in 104873{.interpreted-text role="gh"}.)
  • ~typing.ClassVar{.interpreted-text role="data"} can now be nested in ~typing.Final{.interpreted-text role="data"}, and vice versa. (Contributed by Mehdi Drissi in 89547{.interpreted-text role="gh"}.)

unicodedata

  • Update the Unicode database to version 15.1.0. (Contributed by James Gerity in 109559{.interpreted-text role="gh"}.)

venv

  • Add support for creating source control management (SCM) ignore files in a virtual environment's directory. By default, Git is supported. This is implemented as opt-in via the API, which can be extended to support other SCMs (~venv.EnvBuilder{.interpreted-text role="class"} and ~venv.create{.interpreted-text role="func"}), and opt-out via the CLI, using !--without-scm-ignore-files{.interpreted-text role="option"}. (Contributed by Brett Cannon in 108125{.interpreted-text role="gh"}.)

warnings

  • 702{.interpreted-text role="pep"}: The new warnings.deprecated{.interpreted-text role="func"} decorator provides a way to communicate deprecations to a static type checker{.interpreted-text role="term"} and to warn on usage of deprecated classes and functions. A DeprecationWarning{.interpreted-text role="exc"} may also be emitted when a decorated function or class is used at runtime. (Contributed by Jelle Zijlstra in 104003{.interpreted-text role="gh"}.)

xml

  • Allow controlling Expat >=2.6.0 reparse deferral (2023-52425{.interpreted-text role="cve"}) by adding five new methods:

    • xml.etree.ElementTree.XMLParser.flush{.interpreted-text role="meth"}
    • xml.etree.ElementTree.XMLPullParser.flush{.interpreted-text role="meth"}
    • xml.parsers.expat.xmlparser.GetReparseDeferralEnabled{.interpreted-text role="meth"}
    • xml.parsers.expat.xmlparser.SetReparseDeferralEnabled{.interpreted-text role="meth"}
    • !xml.sax.expatreader.ExpatParser.flush{.interpreted-text role="meth"}

    (Contributed by Sebastian Pipping in 115623{.interpreted-text role="gh"}.)

  • Add the !close{.interpreted-text role="meth"} method for the iterator returned by ~xml.etree.ElementTree.iterparse{.interpreted-text role="func"} for explicit cleanup. (Contributed by Serhiy Storchaka in 69893{.interpreted-text role="gh"}.)

zipimport

  • Add support for ZIP64 format files. Everybody loves huge data, right? (Contributed by Tim Hatch in 94146{.interpreted-text role="gh"}.)

Optimizations

  • Several standard library modules have had their import times significantly improved. For example, the import time of the typing{.interpreted-text role="mod"} module has been reduced by around a third by removing dependencies on re{.interpreted-text role="mod"} and contextlib{.interpreted-text role="mod"}. Other modules to enjoy import-time speedups include email.utils{.interpreted-text role="mod"}, enum{.interpreted-text role="mod"}, functools{.interpreted-text role="mod"}, importlib.metadata{.interpreted-text role="mod"}, and threading{.interpreted-text role="mod"}. (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas, and others in 109653{.interpreted-text role="gh"}.)
  • textwrap.indent{.interpreted-text role="func"} is now around 30% faster than before for large input. (Contributed by Inada Naoki in 107369{.interpreted-text role="gh"}.)
  • The subprocess{.interpreted-text role="mod"} module now uses the ~os.posix_spawn{.interpreted-text role="func"} function in more situations, including when close_fds is True (the default) on many modern platforms. This should provide a notable performance increase when launching processes on FreeBSD and Solaris. See the subprocess <whatsnew313-subprocess>{.interpreted-text role="ref"} section above for details. (Contributed by Jakub Kulik in 113117{.interpreted-text role="gh"}.)

Removed Modules And APIs

PEP 594: Remove "dead batteries" from the standard library {#whatsnew313-pep594}

594{.interpreted-text role="pep"} proposed removing 19 modules from the standard library, colloquially referred to as 'dead batteries' due to their historic, obsolete, or insecure status. All of the following modules were deprecated in Python 3.11, and are now removed:

  • !aifc{.interpreted-text role="mod"}
    • standard-aifc{.interpreted-text role="pypi"}: Use the redistribution of aifc library from PyPI.
  • !audioop{.interpreted-text role="mod"}
    • audioop-lts{.interpreted-text role="pypi"}: Use audioop-lts library from PyPI.
  • !chunk{.interpreted-text role="mod"}
    • standard-chunk{.interpreted-text role="pypi"}: Use the redistribution of chunk library from PyPI.
  • !cgi{.interpreted-text role="mod"} and !cgitb{.interpreted-text role="mod"}
    • !cgi.FieldStorage{.interpreted-text role="class"} can typically be replaced with urllib.parse.parse_qsl{.interpreted-text role="func"} for GET and HEAD requests, and the email.message{.interpreted-text role="mod"} module or the multipart{.interpreted-text role="pypi"} library for POST and PUT requests.

    • !cgi.parse{.interpreted-text role="func"} can be replaced by calling urllib.parse.parse_qs{.interpreted-text role="func"} directly on the desired query string, unless the input is multipart/form-data, which should be replaced as described below for !cgi.parse_multipart{.interpreted-text role="func"}.

    • !cgi.parse_header{.interpreted-text role="func"} can be replaced with the functionality in the email{.interpreted-text role="mod"} package, which implements the same MIME RFCs. For example, with email.message.EmailMessage{.interpreted-text role="class"}:

      from email.message import EmailMessage
      
      msg = EmailMessage()
      msg['content-type'] = 'application/json; charset="utf8"'
      main, params = msg.get_content_type(), msg['content-type'].params
      
    • !cgi.parse_multipart{.interpreted-text role="func"} can be replaced with the functionality in the email{.interpreted-text role="mod"} package, which implements the same MIME RFCs, or with the multipart{.interpreted-text role="pypi"} library. For example, the email.message.EmailMessage{.interpreted-text role="class"} and email.message.Message{.interpreted-text role="class"} classes.

    • standard-cgi{.interpreted-text role="pypi"}: and standard-cgitb{.interpreted-text role="pypi"}: Use the redistribution of cgi and cgitb library from PyPI.

  • !crypt{.interpreted-text role="mod"} and the private !_crypt{.interpreted-text role="mod"} extension. The hashlib{.interpreted-text role="mod"} module may be an appropriate replacement when simply hashing a value is required. Otherwise, various third-party libraries on PyPI are available:
    • bcrypt{.interpreted-text role="pypi"}: Modern password hashing for your software and your servers.
    • argon2-cffi{.interpreted-text role="pypi"}: The secure Argon2 password hashing algorithm.
    • legacycrypt{.interpreted-text role="pypi"}: ctypes{.interpreted-text role="mod"} wrapper to the POSIX crypt library call and associated functionality.
    • crypt_r{.interpreted-text role="pypi"}: Fork of the !crypt{.interpreted-text role="mod"} module, wrapper to the crypt_r(3){.interpreted-text role="manpage"} library call and associated functionality.
    • standard-crypt{.interpreted-text role="pypi"} and deprecated-crypt-alternative{.interpreted-text role="pypi"}: Use the redistribution of crypt and reimplementation of _crypt libraries from PyPI.
  • !imghdr{.interpreted-text role="mod"}: The filetype{.interpreted-text role="pypi"}, puremagic{.interpreted-text role="pypi"}, or python-magic{.interpreted-text role="pypi"} libraries should be used as replacements. For example, the !puremagic.what{.interpreted-text role="func"} function can be used to replace the !imghdr.what{.interpreted-text role="func"} function for all file formats that were supported by !imghdr{.interpreted-text role="mod"}.
    • standard-imghdr{.interpreted-text role="pypi"}: Use the redistribution of imghdr library from PyPI.
  • !mailcap{.interpreted-text role="mod"}: Use the mimetypes{.interpreted-text role="mod"} module instead.
    • standard-mailcap{.interpreted-text role="pypi"}: Use the redistribution of mailcap library from PyPI.
  • !msilib{.interpreted-text role="mod"}
  • !nis{.interpreted-text role="mod"}
  • !nntplib{.interpreted-text role="mod"}: Use the pynntp{.interpreted-text role="pypi"} library from PyPI instead.
    • standard-nntplib{.interpreted-text role="pypi"}: Use the redistribution of nntplib library from PyPI.
  • !ossaudiodev{.interpreted-text role="mod"}: For audio playback, use the pygame{.interpreted-text role="pypi"} library from PyPI instead.
  • !pipes{.interpreted-text role="mod"}: Use the subprocess{.interpreted-text role="mod"} module instead. Use shlex.quote{.interpreted-text role="func"} to replace the undocumented pipes.quote function.
    • standard-pipes{.interpreted-text role="pypi"}: Use the redistribution of pipes library from PyPI.
  • !sndhdr{.interpreted-text role="mod"}: The filetype{.interpreted-text role="pypi"}, puremagic{.interpreted-text role="pypi"}, or python-magic{.interpreted-text role="pypi"} libraries should be used as replacements.
    • standard-sndhdr{.interpreted-text role="pypi"}: Use the redistribution of sndhdr library from PyPI.
  • !spwd{.interpreted-text role="mod"}: Use the python-pam{.interpreted-text role="pypi"} library from PyPI instead.
  • !sunau{.interpreted-text role="mod"}
    • standard-sunau{.interpreted-text role="pypi"}: Use the redistribution of sunau library from PyPI.
  • !telnetlib{.interpreted-text role="mod"}, Use the telnetlib3{.interpreted-text role="pypi"} or Exscript{.interpreted-text role="pypi"} libraries from PyPI instead.
    • standard-telnetlib{.interpreted-text role="pypi"}: Use the redistribution of telnetlib library from PyPI.
  • !uu{.interpreted-text role="mod"}: Use the base64{.interpreted-text role="mod"} module instead, as a modern alternative.
    • standard-uu{.interpreted-text role="pypi"}: Use the redistribution of uu library from PyPI.
  • !xdrlib{.interpreted-text role="mod"}
    • standard-xdrlib{.interpreted-text role="pypi"}: Use the redistribution of xdrlib library from PyPI.

(Contributed by Victor Stinner and Zachary Ware in 104773{.interpreted-text role="gh"} and 104780{.interpreted-text role="gh"}.)

2to3

  • Remove the 2to3{.interpreted-text role="program"} program and the !lib2to3{.interpreted-text role="mod"} module, previously deprecated in Python 3.11. (Contributed by Victor Stinner in 104780{.interpreted-text role="gh"}.)

builtins

  • Remove support for chained classmethod{.interpreted-text role="class"} descriptors (introduced in 63272{.interpreted-text role="gh"}). These can no longer be used to wrap other descriptors, such as property{.interpreted-text role="class"}. The core design of this feature was flawed and led to several problems. To "pass-through" a classmethod{.interpreted-text role="class"}, consider using the !__wrapped__{.interpreted-text role="attr"} attribute that was added in Python 3.10. (Contributed by Raymond Hettinger in 89519{.interpreted-text role="gh"}.)
  • Raise a RuntimeError{.interpreted-text role="exc"} when calling frame.clear{.interpreted-text role="meth"} on a suspended frame (as has always been the case for an executing frame). (Contributed by Irit Katriel in 79932{.interpreted-text role="gh"}.)

configparser

  • Remove the undocumented !LegacyInterpolation{.interpreted-text role="class"} class, deprecated in the docstring since Python 3.2, and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in 104886{.interpreted-text role="gh"}.)

importlib.metadata

  • Remove deprecated subscript (~object.__getitem__{.interpreted-text role="meth"}) access for EntryPoint <entry-points>{.interpreted-text role="ref"} objects. (Contributed by Jason R. Coombs in 113175{.interpreted-text role="gh"}.)

locale

  • Remove the !locale.resetlocale{.interpreted-text role="func"} function, deprecated in Python 3.11. Use locale.setlocale(locale.LC_ALL, "") instead. (Contributed by Victor Stinner in 104783{.interpreted-text role="gh"}.)

opcode

  • Move !opcode.ENABLE_SPECIALIZATION{.interpreted-text role="attr"} to !_opcode.ENABLE_SPECIALIZATION{.interpreted-text role="attr"}. This field was added in 3.12, it was never documented, and is not intended for external use. (Contributed by Irit Katriel in 105481{.interpreted-text role="gh"}.)
  • Remove !opcode.is_pseudo{.interpreted-text role="func"}, !opcode.MIN_PSEUDO_OPCODE{.interpreted-text role="attr"}, and !opcode.MAX_PSEUDO_OPCODE{.interpreted-text role="attr"}, which were added in Python 3.12, but were neither documented nor exposed through dis{.interpreted-text role="mod"}, and were not intended to be used externally. (Contributed by Irit Katriel in 105481{.interpreted-text role="gh"}.)

optparse

  • This module is no longer considered soft deprecated{.interpreted-text role="term"}. While argparse{.interpreted-text role="mod"} remains preferred for new projects that aren't using a third party command line argument processing library, there are aspects of the way argparse works that mean the lower level optparse module may provide a better foundation for writing argument processing libraries, and for implementing command line applications which adhere more strictly than argparse does to various Unix command line processing conventions that originate in the behaviour of the C !getopt{.interpreted-text role="c:func"} function . (Contributed by Alyssa Coghlan and Serhiy Storchaka in 126180{.interpreted-text role="gh"}.)

pathlib

  • Remove the ability to use ~pathlib.Path{.interpreted-text role="class"} objects as context managers. This functionality was deprecated and has had no effect since Python 3.9. (Contributed by Barney Gale in 83863{.interpreted-text role="gh"}.)

re

  • Remove the undocumented, deprecated, and broken !re.template{.interpreted-text role="func"} function and !re.TEMPLATE{.interpreted-text role="attr"} / !re.T{.interpreted-text role="attr"} flag. (Contributed by Serhiy Storchaka and Nikita Sobolev in 105687{.interpreted-text role="gh"}.)

tkinter.tix

  • Remove the !tkinter.tix{.interpreted-text role="mod"} module, deprecated in Python 3.6. The third-party Tix library which the module wrapped is unmaintained. (Contributed by Zachary Ware in 75552{.interpreted-text role="gh"}.)

turtle

  • Remove the !RawTurtle.settiltangle{.interpreted-text role="meth"} method, deprecated in the documentation since Python 3.1 and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in 104876{.interpreted-text role="gh"}.)

typing

  • Remove the !typing.io{.interpreted-text role="mod"} and !typing.re{.interpreted-text role="mod"} namespaces, deprecated since Python 3.8. The items in those namespaces can be imported directly from the typing{.interpreted-text role="mod"} module. (Contributed by Sebastian Rittau in 92871{.interpreted-text role="gh"}.)
  • Remove the keyword-argument method of creating ~typing.TypedDict{.interpreted-text role="class"} types, deprecated in Python 3.11. (Contributed by Tomas Roun in 104786{.interpreted-text role="gh"}.)

unittest

  • Remove the following unittest{.interpreted-text role="mod"} functions, deprecated in Python 3.11:

    • !unittest.findTestCases{.interpreted-text role="func"}
    • !unittest.makeSuite{.interpreted-text role="func"}
    • !unittest.getTestCaseNames{.interpreted-text role="func"}

    Use ~unittest.TestLoader{.interpreted-text role="class"} methods instead:

    • ~unittest.TestLoader.loadTestsFromModule{.interpreted-text role="meth"}
    • ~unittest.TestLoader.loadTestsFromTestCase{.interpreted-text role="meth"}
    • ~unittest.TestLoader.getTestCaseNames{.interpreted-text role="meth"}

    (Contributed by Hugo van Kemenade in 104835{.interpreted-text role="gh"}.)

  • Remove the untested and undocumented !TestProgram.usageExit{.interpreted-text role="meth"} method, deprecated in Python 3.11. (Contributed by Hugo van Kemenade in 104992{.interpreted-text role="gh"}.)

urllib

  • Remove the cafile, capath, and cadefault parameters of the urllib.request.urlopen{.interpreted-text role="func"} function, deprecated in Python 3.6. Use the context parameter instead with an ~ssl.SSLContext{.interpreted-text role="class"} instance. The ssl.SSLContext.load_cert_chain{.interpreted-text role="meth"} function can be used to load specific certificates, or let ssl.create_default_context{.interpreted-text role="func"} select the operating system's trusted certificate authority (CA) certificates. (Contributed by Victor Stinner in 105382{.interpreted-text role="gh"}.)

webbrowser

  • Remove the untested and undocumented !MacOSX{.interpreted-text role="class"} class, deprecated in Python 3.11. Use the !MacOSXOSAScript{.interpreted-text role="class"} class (introduced in Python 3.2) instead. (Contributed by Hugo van Kemenade in 104804{.interpreted-text role="gh"}.)
  • Remove the deprecated !MacOSXOSAScript._name{.interpreted-text role="attr"} attribute. Use the MacOSXOSAScript.name <webbrowser.controller.name>{.interpreted-text role="attr"} attribute instead. (Contributed by Nikita Sobolev in 105546{.interpreted-text role="gh"}.)

New Deprecations

  • User-defined functions <user-defined-funcs>{.interpreted-text role="ref"}:
    • Deprecate assignment to a function's ~function.__code__{.interpreted-text role="attr"} attribute, where the new code object's type does not match the function's type. The different types are: plain function, generator, async generator, and coroutine. (Contributed by Irit Katriel in 81137{.interpreted-text role="gh"}.)
  • array{.interpreted-text role="mod"}:
    • Deprecate the 'u' format code (wchar_t{.interpreted-text role="c:type"}) at runtime. This format code has been deprecated in documentation since Python 3.3, and will be removed in Python 3.16. Use the 'w' format code (Py_UCS4{.interpreted-text role="c:type"}) for Unicode characters instead. (Contributed by Hugo van Kemenade in 80480{.interpreted-text role="gh"}.)
  • ctypes{.interpreted-text role="mod"}:
    • Deprecate the undocumented !SetPointerType{.interpreted-text role="func"} function, to be removed in Python 3.15. (Contributed by Victor Stinner in 105733{.interpreted-text role="gh"}.)
    • Soft-deprecate <soft deprecated>{.interpreted-text role="term"} the ~ctypes.ARRAY{.interpreted-text role="func"} function in favour of type * length multiplication. (Contributed by Victor Stinner in 105733{.interpreted-text role="gh"}.)
  • decimal{.interpreted-text role="mod"}:
    • Deprecate the non-standard and undocumented ~decimal.Decimal{.interpreted-text role="class"} format specifier 'N', which is only supported in the !decimal{.interpreted-text role="mod"} module's C implementation. Scheduled to be removed in Python 3.18. (Contributed by Serhiy Storchaka in 89902{.interpreted-text role="gh"}.)
  • dis{.interpreted-text role="mod"}:
    • Deprecate the !HAVE_ARGUMENT{.interpreted-text role="attr"} separator. Check membership in ~dis.hasarg{.interpreted-text role="data"} instead. (Contributed by Irit Katriel in 109319{.interpreted-text role="gh"}.)
  • gettext{.interpreted-text role="mod"}:
    • Deprecate non-integer numbers as arguments to functions and methods that consider plural forms in the !gettext{.interpreted-text role="mod"} module, even if no translation was found. (Contributed by Serhiy Storchaka in 88434{.interpreted-text role="gh"}.)
  • glob{.interpreted-text role="mod"}:
    • Deprecate the undocumented !glob0{.interpreted-text role="func"} and !glob1{.interpreted-text role="func"} functions. Use ~glob.glob{.interpreted-text role="func"} and pass a path-like object{.interpreted-text role="term"} specifying the root directory to the root_dir parameter instead. (Contributed by Barney Gale in 117337{.interpreted-text role="gh"}.)
  • http.server{.interpreted-text role="mod"}:
    • Deprecate !CGIHTTPRequestHandler{.interpreted-text role="class"}, to be removed in Python 3.15. Process-based CGI HTTP servers have been out of favor for a very long time. This code was outdated, unmaintained, and rarely used. It has a high potential for both security and functionality bugs. (Contributed by Gregory P. Smith in 109096{.interpreted-text role="gh"}.)
    • Deprecate the !--cgi{.interpreted-text role="option"} flag to the python -m http.server{.interpreted-text role="program"} command-line interface, to be removed in Python 3.15. (Contributed by Gregory P. Smith in 109096{.interpreted-text role="gh"}.)
  • mimetypes{.interpreted-text role="mod"}:
    • Soft-deprecate <soft deprecated>{.interpreted-text role="term"} file path arguments to ~mimetypes.guess_type{.interpreted-text role="func"}, use ~mimetypes.guess_file_type{.interpreted-text role="func"} instead. (Contributed by Serhiy Storchaka in 66543{.interpreted-text role="gh"}.)
  • re{.interpreted-text role="mod"}:
    • Deprecate passing the optional maxsplit, count, or flags arguments as positional arguments to the module-level ~re.split{.interpreted-text role="func"}, ~re.sub{.interpreted-text role="func"}, and ~re.subn{.interpreted-text role="func"} functions. These parameters will become keyword-only <keyword-only_parameter>{.interpreted-text role="ref"} in a future version of Python. (Contributed by Serhiy Storchaka in 56166{.interpreted-text role="gh"}.)
  • pathlib{.interpreted-text role="mod"}:
    • Deprecate !.PurePath.is_reserved{.interpreted-text role="meth"}, to be removed in Python 3.15. Use os.path.isreserved{.interpreted-text role="func"} to detect reserved paths on Windows. (Contributed by Barney Gale in 88569{.interpreted-text role="gh"}.)
  • platform{.interpreted-text role="mod"}:
    • Deprecate !platform.java_ver{.interpreted-text role="func"}, to be removed in Python 3.15. This function is only useful for Jython support, has a confusing API, and is largely untested. (Contributed by Nikita Sobolev in 116349{.interpreted-text role="gh"}.)
  • pydoc{.interpreted-text role="mod"}:
    • Deprecate the undocumented !ispackage{.interpreted-text role="func"} function. (Contributed by Zackery Spytz in 64020{.interpreted-text role="gh"}.)
  • sqlite3{.interpreted-text role="mod"}:
    • Deprecate passing more than one positional argument to the ~sqlite3.connect{.interpreted-text role="func"} function and the ~sqlite3.Connection{.interpreted-text role="class"} constructor. The remaining parameters will become keyword-only in Python 3.15. (Contributed by Erlend E. Aasland in 107948{.interpreted-text role="gh"}.)
    • Deprecate passing name, number of arguments, and the callable as keyword arguments for .Connection.create_function{.interpreted-text role="meth"} and .Connection.create_aggregate{.interpreted-text role="meth"} These parameters will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in 108278{.interpreted-text role="gh"}.)
    • Deprecate passing the callback callable by keyword for the ~sqlite3.Connection.set_authorizer{.interpreted-text role="meth"}, ~sqlite3.Connection.set_progress_handler{.interpreted-text role="meth"}, and ~sqlite3.Connection.set_trace_callback{.interpreted-text role="meth"} ~sqlite3.Connection{.interpreted-text role="class"} methods. The callback callables will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in 108278{.interpreted-text role="gh"}.)
  • sys{.interpreted-text role="mod"}:
    • Deprecate the ~sys._enablelegacywindowsfsencoding{.interpreted-text role="func"} function, to be removed in Python 3.16. Use the PYTHONLEGACYWINDOWSFSENCODING{.interpreted-text role="envvar"} environment variable instead. (Contributed by Inada Naoki in 73427{.interpreted-text role="gh"}.)
  • tarfile{.interpreted-text role="mod"}:
    • Deprecate the undocumented and unused !TarFile.tarfile{.interpreted-text role="attr"} attribute, to be removed in Python 3.16. (Contributed in 115256{.interpreted-text role="gh"}.)
  • traceback{.interpreted-text role="mod"}:
    • Deprecate the .TracebackException.exc_type{.interpreted-text role="attr"} attribute. Use .TracebackException.exc_type_str{.interpreted-text role="attr"} instead. (Contributed by Irit Katriel in 112332{.interpreted-text role="gh"}.)
  • typing{.interpreted-text role="mod"}:
    • Deprecate the undocumented keyword argument syntax for creating ~typing.NamedTuple{.interpreted-text role="class"} classes (e.g. Point = NamedTuple("Point", x=int, y=int)), to be removed in Python 3.15. Use the class-based syntax or the functional syntax instead. (Contributed by Alex Waygood in 105566{.interpreted-text role="gh"}.)
    • Deprecate omitting the fields parameter when creating a ~typing.NamedTuple{.interpreted-text role="class"} or typing.TypedDict{.interpreted-text role="class"} class, and deprecate passing None to the fields parameter of both types. Python 3.15 will require a valid sequence for the fields parameter. To create a NamedTuple class with zero fields, use class NT(NamedTuple): pass or NT = NamedTuple("NT", ()). To create a TypedDict class with zero fields, use class TD(TypedDict): pass or TD = TypedDict("TD", {}). (Contributed by Alex Waygood in 105566{.interpreted-text role="gh"} and 105570{.interpreted-text role="gh"}.)
    • Deprecate the !typing.no_type_check_decorator{.interpreted-text role="func"} decorator function, to be removed in Python 3.15. After eight years in the typing{.interpreted-text role="mod"} module, it has yet to be supported by any major type checker. (Contributed by Alex Waygood in 106309{.interpreted-text role="gh"}.)
    • Deprecate typing.AnyStr{.interpreted-text role="data"}. In Python 3.16, it will be removed from typing.__all__, and a DeprecationWarning{.interpreted-text role="exc"} will be emitted at runtime when it is imported or accessed. It will be removed entirely in Python 3.18. Use the new type parameter syntax <type-params>{.interpreted-text role="ref"} instead. (Contributed by Michael The in 107116{.interpreted-text role="gh"}.)
  • wave{.interpreted-text role="mod"}:
    • Deprecate the getmark(), setmark() and getmarkers() methods of the ~wave.Wave_read{.interpreted-text role="class"} and ~wave.Wave_write{.interpreted-text role="class"} classes, to be removed in Python 3.15. (Contributed by Victor Stinner in 105096{.interpreted-text role="gh"}.)

Pending removal in Python 3.14

  • argparse{.interpreted-text role="mod"}: The type, choices, and metavar parameters of !argparse.BooleanOptionalAction{.interpreted-text role="class"} are deprecated and will be removed in 3.14. (Contributed by Nikita Sobolev in 92248{.interpreted-text role="gh"}.)

  • ast{.interpreted-text role="mod"}: The following features have been deprecated in documentation since Python 3.8, now cause a DeprecationWarning{.interpreted-text role="exc"} to be emitted at runtime when they are accessed or used, and will be removed in Python 3.14:

    • !ast.Num{.interpreted-text role="class"}
    • !ast.Str{.interpreted-text role="class"}
    • !ast.Bytes{.interpreted-text role="class"}
    • !ast.NameConstant{.interpreted-text role="class"}
    • !ast.Ellipsis{.interpreted-text role="class"}

    Use ast.Constant{.interpreted-text role="class"} instead. (Contributed by Serhiy Storchaka in 90953{.interpreted-text role="gh"}.)

  • asyncio{.interpreted-text role="mod"}:

    • The child watcher classes !asyncio.MultiLoopChildWatcher{.interpreted-text role="class"}, !asyncio.FastChildWatcher{.interpreted-text role="class"}, !asyncio.AbstractChildWatcher{.interpreted-text role="class"} and !asyncio.SafeChildWatcher{.interpreted-text role="class"} are deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in 94597{.interpreted-text role="gh"}.)
    • !asyncio.set_child_watcher{.interpreted-text role="func"}, !asyncio.get_child_watcher{.interpreted-text role="func"}, !asyncio.AbstractEventLoopPolicy.set_child_watcher{.interpreted-text role="meth"} and !asyncio.AbstractEventLoopPolicy.get_child_watcher{.interpreted-text role="meth"} are deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in 94597{.interpreted-text role="gh"}.)
    • The ~asyncio.get_event_loop{.interpreted-text role="meth"} method of the default event loop policy now emits a DeprecationWarning{.interpreted-text role="exc"} if there is no current event loop set and it decides to create one. (Contributed by Serhiy Storchaka and Guido van Rossum in 100160{.interpreted-text role="gh"}.)
  • email{.interpreted-text role="mod"}: Deprecated the isdst parameter in email.utils.localtime{.interpreted-text role="func"}. (Contributed by Alan Williams in 72346{.interpreted-text role="gh"}.)

  • importlib.abc{.interpreted-text role="mod"} deprecated classes:

    • !importlib.abc.ResourceReader{.interpreted-text role="class"}
    • !importlib.abc.Traversable{.interpreted-text role="class"}
    • !importlib.abc.TraversableResources{.interpreted-text role="class"}

    Use importlib.resources.abc{.interpreted-text role="mod"} classes instead:

    • importlib.resources.abc.Traversable{.interpreted-text role="class"}
    • importlib.resources.abc.TraversableResources{.interpreted-text role="class"}

    (Contributed by Jason R. Coombs and Hugo van Kemenade in 93963{.interpreted-text role="gh"}.)

  • itertools{.interpreted-text role="mod"} had undocumented, inefficient, historically buggy, and inconsistent support for copy, deepcopy, and pickle operations. This will be removed in 3.14 for a significant reduction in code volume and maintenance burden. (Contributed by Raymond Hettinger in 101588{.interpreted-text role="gh"}.)

  • multiprocessing{.interpreted-text role="mod"}: The default start method will change to a safer one on Linux, BSDs, and other non-macOS POSIX platforms where 'fork' is currently the default (84559{.interpreted-text role="gh"}). Adding a runtime warning about this was deemed too disruptive as the majority of code is not expected to care. Use the ~multiprocessing.get_context{.interpreted-text role="func"} or ~multiprocessing.set_start_method{.interpreted-text role="func"} APIs to explicitly specify when your code requires 'fork'. See multiprocessing-start-methods{.interpreted-text role="ref"}.

  • pathlib{.interpreted-text role="mod"}: ~pathlib.PurePath.is_relative_to{.interpreted-text role="meth"} and ~pathlib.PurePath.relative_to{.interpreted-text role="meth"}: passing additional arguments is deprecated.

  • pkgutil{.interpreted-text role="mod"}: !pkgutil.find_loader{.interpreted-text role="func"} and !pkgutil.get_loader{.interpreted-text role="func"} now raise DeprecationWarning{.interpreted-text role="exc"}; use importlib.util.find_spec{.interpreted-text role="func"} instead. (Contributed by Nikita Sobolev in 97850{.interpreted-text role="gh"}.)

  • pty{.interpreted-text role="mod"}:

    • master_open(): use pty.openpty{.interpreted-text role="func"}.
    • slave_open(): use pty.openpty{.interpreted-text role="func"}.
  • sqlite3{.interpreted-text role="mod"}:

    • !version{.interpreted-text role="data"} and !version_info{.interpreted-text role="data"}.
    • ~sqlite3.Cursor.execute{.interpreted-text role="meth"} and ~sqlite3.Cursor.executemany{.interpreted-text role="meth"} if named placeholders <sqlite3-placeholders>{.interpreted-text role="ref"} are used and parameters is a sequence instead of a dict{.interpreted-text role="class"}.
  • urllib{.interpreted-text role="mod"}: !urllib.parse.Quoter{.interpreted-text role="class"} is deprecated: it was not intended to be a public API. (Contributed by Gregory P. Smith in 88168{.interpreted-text role="gh"}.)

Pending removal in Python 3.15

  • The import system:
    • Setting __cached__ on a module while failing to set __spec__.cached <importlib.machinery.ModuleSpec.cached>{.interpreted-text role="attr"} is deprecated. In Python 3.15, __cached__ will cease to be set or take into consideration by the import system or standard library. (97879{.interpreted-text role="gh"})
    • Setting ~module.__package__{.interpreted-text role="attr"} on a module while failing to set __spec__.parent <importlib.machinery.ModuleSpec.parent>{.interpreted-text role="attr"} is deprecated. In Python 3.15, !__package__{.interpreted-text role="attr"} will cease to be set or take into consideration by the import system or standard library. (97879{.interpreted-text role="gh"})
  • ctypes{.interpreted-text role="mod"}:
    • The undocumented !ctypes.SetPointerType{.interpreted-text role="func"} function has been deprecated since Python 3.13.
  • http.server{.interpreted-text role="mod"}:
    • The obsolete and rarely used !CGIHTTPRequestHandler{.interpreted-text role="class"} has been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler.
    • The !--cgi{.interpreted-text role="option"} flag to the python -m http.server{.interpreted-text role="program"} command-line interface has been deprecated since Python 3.13.
  • importlib{.interpreted-text role="mod"}:
    • load_module() method: use exec_module() instead.
  • pathlib{.interpreted-text role="mod"}:
    • !.PurePath.is_reserved{.interpreted-text role="meth"} has been deprecated since Python 3.13. Use os.path.isreserved{.interpreted-text role="func"} to detect reserved paths on Windows.
  • platform{.interpreted-text role="mod"}:
    • !platform.java_ver{.interpreted-text role="func"} has been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.
  • sysconfig{.interpreted-text role="mod"}:
    • The check_home argument of sysconfig.is_python_build{.interpreted-text role="func"} has been deprecated since Python 3.12.
  • threading{.interpreted-text role="mod"}:
    • ~threading.RLock{.interpreted-text role="func"} will take no arguments in Python 3.15. Passing any arguments has been deprecated since Python 3.14, as the Python version does not permit any arguments, but the C version allows any number of positional or keyword arguments, ignoring every argument.
  • types{.interpreted-text role="mod"}:
    • types.CodeType{.interpreted-text role="class"}: Accessing ~codeobject.co_lnotab{.interpreted-text role="attr"} was deprecated in 626{.interpreted-text role="pep"} since 3.10 and was planned to be removed in 3.12, but it only got a proper DeprecationWarning{.interpreted-text role="exc"} in 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in 101866{.interpreted-text role="gh"}.)
  • typing{.interpreted-text role="mod"}:
    • The undocumented keyword argument syntax for creating ~typing.NamedTuple{.interpreted-text role="class"} classes (for example, Point = NamedTuple("Point", x=int, y=int)) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead.
    • When using the functional syntax of ~typing.TypedDict{.interpreted-text role="class"}s, failing to pass a value to the fields parameter (TD = TypedDict("TD")) or passing None (TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Use class TD(TypedDict): pass or TD = TypedDict("TD", {}) to create a TypedDict with zero field.
    • The !typing.no_type_check_decorator{.interpreted-text role="func"} decorator function has been deprecated since Python 3.13. After eight years in the typing{.interpreted-text role="mod"} module, it has yet to be supported by any major type checker.
  • !sre_compile{.interpreted-text role="mod"}, !sre_constants{.interpreted-text role="mod"} and !sre_parse{.interpreted-text role="mod"} modules.
  • wave{.interpreted-text role="mod"}:
    • The getmark(), setmark() and getmarkers() methods of the ~wave.Wave_read{.interpreted-text role="class"} and ~wave.Wave_write{.interpreted-text role="class"} classes have been deprecated since Python 3.13.
  • zipimport{.interpreted-text role="mod"}:
    • !zipimport.zipimporter.load_module{.interpreted-text role="meth"} has been deprecated since Python 3.10. Use ~zipimport.zipimporter.exec_module{.interpreted-text role="meth"} instead. (125746{.interpreted-text role="gh"}.)

Pending removal in Python 3.16

  • The import system:
    • Setting ~module.__loader__{.interpreted-text role="attr"} on a module while failing to set __spec__.loader <importlib.machinery.ModuleSpec.loader>{.interpreted-text role="attr"} is deprecated. In Python 3.16, !__loader__{.interpreted-text role="attr"} will cease to be set or taken into consideration by the import system or the standard library.
  • array{.interpreted-text role="mod"}:
    • The 'u' format code (wchar_t{.interpreted-text role="c:type"}) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the 'w' format code (Py_UCS4{.interpreted-text role="c:type"}) for Unicode characters instead.
  • asyncio{.interpreted-text role="mod"}:
    • !asyncio.iscoroutinefunction{.interpreted-text role="func"} is deprecated and will be removed in Python 3.16; use inspect.iscoroutinefunction{.interpreted-text role="func"} instead. (Contributed by Jiahao Li and Kumar Aditya in 122875{.interpreted-text role="gh"}.)

    • asyncio{.interpreted-text role="mod"} policy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:

      • asyncio.AbstractEventLoopPolicy{.interpreted-text role="class"}
      • asyncio.DefaultEventLoopPolicy{.interpreted-text role="class"}
      • asyncio.WindowsSelectorEventLoopPolicy{.interpreted-text role="class"}
      • asyncio.WindowsProactorEventLoopPolicy{.interpreted-text role="class"}
      • asyncio.get_event_loop_policy{.interpreted-text role="func"}
      • asyncio.set_event_loop_policy{.interpreted-text role="func"}

      Users should use asyncio.run{.interpreted-text role="func"} or asyncio.Runner{.interpreted-text role="class"} with loop_factory to use the desired event loop implementation.

      For example, to use asyncio.SelectorEventLoop{.interpreted-text role="class"} on Windows:

      import asyncio
      
      async def main():
          ...
      
      asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
      

      (Contributed by Kumar Aditya in 127949{.interpreted-text role="gh"}.)

  • builtins{.interpreted-text role="mod"}:
    • Bitwise inversion on boolean types, ~True or ~False has been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2 and -1). Use not x instead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert to int explicitly (~int(x)).
  • functools{.interpreted-text role="mod"}:
    • Calling the Python implementation of functools.reduce{.interpreted-text role="func"} with function or sequence as keyword arguments has been deprecated since Python 3.14.
  • logging{.interpreted-text role="mod"}:
    • Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in 115032{.interpreted-text role="gh"}.)
  • mimetypes{.interpreted-text role="mod"}:
    • Valid extensions start with a '.' or are empty for mimetypes.MimeTypes.add_type{.interpreted-text role="meth"}. Undotted extensions are deprecated and will raise a ValueError{.interpreted-text role="exc"} in Python 3.16. (Contributed by Hugo van Kemenade in 75223{.interpreted-text role="gh"}.)
  • shutil{.interpreted-text role="mod"}:
    • The !ExecError{.interpreted-text role="class"} exception has been deprecated since Python 3.14. It has not been used by any function in !shutil{.interpreted-text role="mod"} since Python 3.4, and is now an alias of RuntimeError{.interpreted-text role="exc"}.
  • symtable{.interpreted-text role="mod"}:
    • The Class.get_methods <symtable.Class.get_methods>{.interpreted-text role="meth"} method has been deprecated since Python 3.14.
  • sys{.interpreted-text role="mod"}:
    • The ~sys._enablelegacywindowsfsencoding{.interpreted-text role="func"} function has been deprecated since Python 3.13. Use the PYTHONLEGACYWINDOWSFSENCODING{.interpreted-text role="envvar"} environment variable instead.
  • sysconfig{.interpreted-text role="mod"}:
    • The !sysconfig.expand_makefile_vars{.interpreted-text role="func"} function has been deprecated since Python 3.14. Use the vars argument of sysconfig.get_paths{.interpreted-text role="func"} instead.
  • tarfile{.interpreted-text role="mod"}:
    • The undocumented and unused !TarFile.tarfile{.interpreted-text role="attr"} attribute has been deprecated since Python 3.13.

Pending removal in Python 3.17

  • collections.abc{.interpreted-text role="mod"}:
    • collections.abc.ByteString{.interpreted-text role="class"} is scheduled for removal in Python 3.17.

      Use isinstance(obj, collections.abc.Buffer) to test if obj implements the buffer protocol <bufferobjects>{.interpreted-text role="ref"} at runtime. For use in type annotations, either use ~collections.abc.Buffer{.interpreted-text role="class"} or a union that explicitly specifies the types your code supports (e.g., bytes | bytearray | memoryview).

      !ByteString{.interpreted-text role="class"} was originally intended to be an abstract class that would serve as a supertype of both bytes{.interpreted-text role="class"} and bytearray{.interpreted-text role="class"}. However, since the ABC never had any methods, knowing that an object was an instance of !ByteString{.interpreted-text role="class"} never actually told you anything useful about the object. Other common buffer types such as memoryview{.interpreted-text role="class"} were also never understood as subtypes of !ByteString{.interpreted-text role="class"} (either at runtime or by static type checkers).

      See PEP 688 <688#current-options>{.interpreted-text role="pep"} for more details. (Contributed by Shantanu Jain in 91896{.interpreted-text role="gh"}.)

  • encodings{.interpreted-text role="mod"}:
    • Passing non-ascii encoding names to encodings.normalize_encoding{.interpreted-text role="func"} is deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in 136702{.interpreted-text role="gh"})
  • typing{.interpreted-text role="mod"}:
    • Before Python 3.14, old-style unions were implemented using the private class typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers like typing.get_origin{.interpreted-text role="func"} and typing.get_args{.interpreted-text role="func"} instead of relying on private implementation details.

    • typing.ByteString{.interpreted-text role="class"}, deprecated since Python 3.9, is scheduled for removal in Python 3.17.

      Use isinstance(obj, collections.abc.Buffer) to test if obj implements the buffer protocol <bufferobjects>{.interpreted-text role="ref"} at runtime. For use in type annotations, either use ~collections.abc.Buffer{.interpreted-text role="class"} or a union that explicitly specifies the types your code supports (e.g., bytes | bytearray | memoryview).

      !ByteString{.interpreted-text role="class"} was originally intended to be an abstract class that would serve as a supertype of both bytes{.interpreted-text role="class"} and bytearray{.interpreted-text role="class"}. However, since the ABC never had any methods, knowing that an object was an instance of !ByteString{.interpreted-text role="class"} never actually told you anything useful about the object. Other common buffer types such as memoryview{.interpreted-text role="class"} were also never understood as subtypes of !ByteString{.interpreted-text role="class"} (either at runtime or by static type checkers).

      See PEP 688 <688#current-options>{.interpreted-text role="pep"} for more details. (Contributed by Shantanu Jain in 91896{.interpreted-text role="gh"}.)

Pending removal in Python 3.18

  • decimal{.interpreted-text role="mod"}:
    • The non-standard and undocumented ~decimal.Decimal{.interpreted-text role="class"} format specifier 'N', which is only supported in the !decimal{.interpreted-text role="mod"} module's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in 89902{.interpreted-text role="gh"}.)

Pending removal in Python 3.19

  • ctypes{.interpreted-text role="mod"}:
    • Implicitly switching to the MSVC-compatible struct layout by setting ~ctypes.Structure._pack_{.interpreted-text role="attr"} but not ~ctypes.Structure._layout_{.interpreted-text role="attr"} on non-Windows platforms.
  • hashlib{.interpreted-text role="mod"}:
    • In hash function constructors such as ~hashlib.new{.interpreted-text role="func"} or the direct hash-named constructors such as ~hashlib.md5{.interpreted-text role="func"} and ~hashlib.sha256{.interpreted-text role="func"}, their optional initial data parameter could also be passed a keyword argument named data= or string= in various !hashlib{.interpreted-text role="mod"} implementations.

      Support for the string keyword argument name is now deprecated and slated for removal in Python 3.19.

      Before Python 3.13, the string keyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.

Pending removal in Python 3.20

  • The __version__, version and VERSION attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Use sys.version_info{.interpreted-text role="py:data"} instead.

    • argparse{.interpreted-text role="mod"}
    • csv{.interpreted-text role="mod"}
    • ctypes{.interpreted-text role="mod"}
    • !ctypes.macholib{.interpreted-text role="mod"}
    • decimal{.interpreted-text role="mod"} (use decimal.SPEC_VERSION{.interpreted-text role="data"} instead)
    • http.server{.interpreted-text role="mod"}
    • imaplib{.interpreted-text role="mod"}
    • ipaddress{.interpreted-text role="mod"}
    • json{.interpreted-text role="mod"}
    • logging{.interpreted-text role="mod"} (__date__ also deprecated)
    • optparse{.interpreted-text role="mod"}
    • pickle{.interpreted-text role="mod"}
    • platform{.interpreted-text role="mod"}
    • re{.interpreted-text role="mod"}
    • socketserver{.interpreted-text role="mod"}
    • tabnanny{.interpreted-text role="mod"}
    • tkinter.font{.interpreted-text role="mod"}
    • tkinter.ttk{.interpreted-text role="mod"}
    • wsgiref.simple_server{.interpreted-text role="mod"}
    • xml.etree.ElementTree{.interpreted-text role="mod"}
    • !xml.sax.expatreader{.interpreted-text role="mod"}
    • xml.sax.handler{.interpreted-text role="mod"}
    • zlib{.interpreted-text role="mod"}

    (Contributed by Hugo van Kemenade and Stan Ulbrych in 76007{.interpreted-text role="gh"}.)

Pending removal in future versions

The following APIs will be removed in the future, although there is currently no date scheduled for their removal.

  • argparse{.interpreted-text role="mod"}:
    • Nesting argument groups and nesting mutually exclusive groups are deprecated.
    • Passing the undocumented keyword argument prefix_chars to ~argparse.ArgumentParser.add_argument_group{.interpreted-text role="meth"} is now deprecated.
    • The argparse.FileType{.interpreted-text role="class"} type converter is deprecated.
  • builtins{.interpreted-text role="mod"}:
    • Generators: throw(type, exc, tb) and athrow(type, exc, tb) signature is deprecated: use throw(exc) and athrow(exc) instead, the single argument signature.
    • Currently Python accepts numeric literals immediately followed by keywords, for example 0in x, 1or x, 0if 1else 2. It allows confusing and ambiguous expressions like [0x1for x in y] (which can be interpreted as [0x1 for x in y] or [0x1f or x in y]). A syntax warning is raised if the numeric literal is immediately followed by one of keywords and{.interpreted-text role="keyword"}, else{.interpreted-text role="keyword"}, for{.interpreted-text role="keyword"}, if{.interpreted-text role="keyword"}, in{.interpreted-text role="keyword"}, is{.interpreted-text role="keyword"} and or{.interpreted-text role="keyword"}. In a future release it will be changed to a syntax error. (87999{.interpreted-text role="gh"})
    • Support for __index__() and __int__() method returning non-int type: these methods will be required to return an instance of a strict subclass of int{.interpreted-text role="class"}.
    • Support for __float__() method returning a strict subclass of float{.interpreted-text role="class"}: these methods will be required to return an instance of float{.interpreted-text role="class"}.
    • Support for __complex__() method returning a strict subclass of complex{.interpreted-text role="class"}: these methods will be required to return an instance of complex{.interpreted-text role="class"}.
    • Passing a complex number as the real or imag argument in the complex{.interpreted-text role="func"} constructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in 109218{.interpreted-text role="gh"}.)
  • calendar{.interpreted-text role="mod"}: calendar.January and calendar.February constants are deprecated and replaced by calendar.JANUARY{.interpreted-text role="data"} and calendar.FEBRUARY{.interpreted-text role="data"}. (Contributed by Prince Roshan in 103636{.interpreted-text role="gh"}.)
  • codecs{.interpreted-text role="mod"}: use open{.interpreted-text role="func"} instead of codecs.open{.interpreted-text role="func"}. (133038{.interpreted-text role="gh"})
  • codeobject.co_lnotab{.interpreted-text role="attr"}: use the codeobject.co_lines{.interpreted-text role="meth"} method instead.
  • datetime{.interpreted-text role="mod"}:
    • ~datetime.datetime.utcnow{.interpreted-text role="meth"}: use datetime.datetime.now(tz=datetime.UTC).
    • ~datetime.datetime.utcfromtimestamp{.interpreted-text role="meth"}: use datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
  • gettext{.interpreted-text role="mod"}: Plural value must be an integer.
  • importlib{.interpreted-text role="mod"}:
    • ~importlib.util.cache_from_source{.interpreted-text role="func"} debug_override parameter is deprecated: use the optimization parameter instead.
  • importlib.metadata{.interpreted-text role="mod"}:
    • EntryPoints tuple interface.
    • Implicit None on return values.
  • logging{.interpreted-text role="mod"}: the warn() method has been deprecated since Python 3.3, use ~logging.warning{.interpreted-text role="meth"} instead.
  • mailbox{.interpreted-text role="mod"}: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.
  • os{.interpreted-text role="mod"}: Calling os.register_at_fork{.interpreted-text role="func"} in a multi-threaded process.
  • os.path{.interpreted-text role="mod"}: os.path.commonprefix{.interpreted-text role="func"} is deprecated, use os.path.commonpath{.interpreted-text role="func"} for path prefixes. The os.path.commonprefix{.interpreted-text role="func"} function is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.
  • !pydoc.ErrorDuringImport{.interpreted-text role="class"}: A tuple value for exc_info parameter is deprecated, use an exception instance.
  • re{.interpreted-text role="mod"}: More strict rules are now applied for numerical group references and group names in regular expressions. Only sequence of ASCII digits is now accepted as a numerical reference. The group name in bytes patterns and replacement strings can now only contain ASCII letters and digits and underscore. (Contributed by Serhiy Storchaka in 91760{.interpreted-text role="gh"}.)
  • shutil{.interpreted-text role="mod"}: ~shutil.rmtree{.interpreted-text role="func"}'s onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.
  • ssl{.interpreted-text role="mod"} options and protocols:
    • ssl.SSLContext{.interpreted-text role="class"} without protocol argument is deprecated.
    • ssl.SSLContext{.interpreted-text role="class"}: ~ssl.SSLContext.set_npn_protocols{.interpreted-text role="meth"} and !selected_npn_protocol{.interpreted-text role="meth"} are deprecated: use ALPN instead.
    • ssl.OP_NO_SSL* options
    • ssl.OP_NO_TLS* options
    • ssl.PROTOCOL_SSLv3
    • ssl.PROTOCOL_TLS
    • ssl.PROTOCOL_TLSv1
    • ssl.PROTOCOL_TLSv1_1
    • ssl.PROTOCOL_TLSv1_2
    • ssl.TLSVersion.SSLv3
    • ssl.TLSVersion.TLSv1
    • ssl.TLSVersion.TLSv1_1
  • threading{.interpreted-text role="mod"} methods:
    • !threading.Condition.notifyAll{.interpreted-text role="meth"}: use ~threading.Condition.notify_all{.interpreted-text role="meth"}.
    • !threading.Event.isSet{.interpreted-text role="meth"}: use ~threading.Event.is_set{.interpreted-text role="meth"}.
    • !threading.Thread.isDaemon{.interpreted-text role="meth"}, threading.Thread.setDaemon{.interpreted-text role="meth"}: use threading.Thread.daemon{.interpreted-text role="attr"} attribute.
    • !threading.Thread.getName{.interpreted-text role="meth"}, threading.Thread.setName{.interpreted-text role="meth"}: use threading.Thread.name{.interpreted-text role="attr"} attribute.
    • !threading.currentThread{.interpreted-text role="meth"}: use threading.current_thread{.interpreted-text role="meth"}.
    • !threading.activeCount{.interpreted-text role="meth"}: use threading.active_count{.interpreted-text role="meth"}.
  • typing.Text{.interpreted-text role="class"} (92332{.interpreted-text role="gh"}).
  • The internal class typing._UnionGenericAlias is no longer used to implement typing.Union{.interpreted-text role="class"}. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in 105499{.interpreted-text role="gh"}.)
  • unittest.IsolatedAsyncioTestCase{.interpreted-text role="class"}: it is deprecated to return a value that is not None from a test case.
  • urllib.parse{.interpreted-text role="mod"} deprecated functions: ~urllib.parse.urlparse{.interpreted-text role="func"} instead
    • splitattr()
    • splithost()
    • splitnport()
    • splitpasswd()
    • splitport()
    • splitquery()
    • splittag()
    • splittype()
    • splituser()
    • splitvalue()
    • to_bytes()
  • wsgiref{.interpreted-text role="mod"}: SimpleHandler.stdout.write() should not do partial writes.
  • xml.etree.ElementTree{.interpreted-text role="mod"}: Testing the truth value of an ~xml.etree.ElementTree.Element{.interpreted-text role="class"} is deprecated. In a future release it will always return True. Prefer explicit len(elem) or elem is not None tests instead.
  • sys._clear_type_cache{.interpreted-text role="func"} is deprecated: use sys._clear_internal_caches{.interpreted-text role="func"} instead.

CPython Bytecode Changes

  • The oparg of YIELD_VALUE{.interpreted-text role="opcode"} is now 1 if the yield is part of a yield-from or await, and 0 otherwise. The oparg of RESUME{.interpreted-text role="opcode"} was changed to add a bit indicating if the except-depth is 1, which is needed to optimize closing of generators. (Contributed by Irit Katriel in 111354{.interpreted-text role="gh"}.)

C API Changes

New Features

  • Add the PyMonitoring C API <c-api-monitoring>{.interpreted-text role="ref"} for generating 669{.interpreted-text role="pep"} monitoring events:

    • PyMonitoringState{.interpreted-text role="c:type"}
    • PyMonitoring_FirePyStartEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FirePyResumeEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FirePyReturnEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FirePyYieldEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireCallEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireLineEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireJumpEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireBranchEvent
    • PyMonitoring_FireCReturnEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FirePyThrowEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireRaiseEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireCRaiseEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireReraiseEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireExceptionHandledEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FirePyUnwindEvent{.interpreted-text role="c:func"}
    • PyMonitoring_FireStopIterationEvent{.interpreted-text role="c:func"}
    • PyMonitoring_EnterScope{.interpreted-text role="c:func"}
    • PyMonitoring_ExitScope{.interpreted-text role="c:func"}

    (Contributed by Irit Katriel in 111997{.interpreted-text role="gh"}).

  • Add PyMutex{.interpreted-text role="c:type"}, a lightweight mutex that occupies a single byte, and the new PyMutex_Lock{.interpreted-text role="c:func"} and PyMutex_Unlock{.interpreted-text role="c:func"} functions. !PyMutex_Lock{.interpreted-text role="c:func"} will release the GIL{.interpreted-text role="term"} (if currently held) if the operation needs to block. (Contributed by Sam Gross in 108724{.interpreted-text role="gh"}.)

  • Add the PyTime C API <c-api-time>{.interpreted-text role="ref"} to provide access to system clocks:

    • PyTime_t{.interpreted-text role="c:type"}.
    • PyTime_MIN{.interpreted-text role="c:var"} and PyTime_MAX{.interpreted-text role="c:var"}.
    • PyTime_AsSecondsDouble{.interpreted-text role="c:func"}.
    • PyTime_Monotonic{.interpreted-text role="c:func"}.
    • PyTime_MonotonicRaw{.interpreted-text role="c:func"}.
    • PyTime_PerfCounter{.interpreted-text role="c:func"}.
    • PyTime_PerfCounterRaw{.interpreted-text role="c:func"}.
    • PyTime_Time{.interpreted-text role="c:func"}.
    • PyTime_TimeRaw{.interpreted-text role="c:func"}.

    (Contributed by Victor Stinner and Petr Viktorin in 110850{.interpreted-text role="gh"}.)

  • Add the PyDict_ContainsString{.interpreted-text role="c:func"} function with the same behavior as PyDict_Contains{.interpreted-text role="c:func"}, but key is specified as a const char*{.interpreted-text role="c:expr"} UTF-8 encoded bytes string, rather than a PyObject*{.interpreted-text role="c:expr"}. (Contributed by Victor Stinner in 108314{.interpreted-text role="gh"}.)

  • Add the PyDict_GetItemRef{.interpreted-text role="c:func"} and PyDict_GetItemStringRef{.interpreted-text role="c:func"} functions, which behave similarly to PyDict_GetItemWithError{.interpreted-text role="c:func"}, but return a strong reference{.interpreted-text role="term"} instead of a borrowed reference{.interpreted-text role="term"}. Moreover, these functions return -1 on error, removing the need to check !PyErr_Occurred{.interpreted-text role="c:func"}. (Contributed by Victor Stinner in 106004{.interpreted-text role="gh"}.)

  • Add the PyDict_SetDefaultRef{.interpreted-text role="c:func"} function, which behaves similarly to PyDict_SetDefault{.interpreted-text role="c:func"}, but returns a strong reference{.interpreted-text role="term"} instead of a borrowed reference{.interpreted-text role="term"}. This function returns -1 on error, 0 on insertion, and 1 if the key was already present in the dictionary. (Contributed by Sam Gross in 112066{.interpreted-text role="gh"}.)

  • Add the PyDict_Pop{.interpreted-text role="c:func"} and PyDict_PopString{.interpreted-text role="c:func"} functions to remove a key from a dictionary and optionally return the removed value. This is similar to dict.pop{.interpreted-text role="meth"}, though there is no default value, and KeyError{.interpreted-text role="exc"} is not raised for missing keys. (Contributed by Stefan Behnel and Victor Stinner in 111262{.interpreted-text role="gh"}.)

  • Add the PyMapping_GetOptionalItem{.interpreted-text role="c:func"} and PyMapping_GetOptionalItemString{.interpreted-text role="c:func"} functions as alternatives to PyObject_GetItem{.interpreted-text role="c:func"} and PyMapping_GetItemString{.interpreted-text role="c:func"} respectively. The new functions do not raise KeyError{.interpreted-text role="exc"} if the requested key is missing from the mapping. These variants are more convenient and faster if a missing key should not be treated as a failure. (Contributed by Serhiy Storchaka in 106307{.interpreted-text role="gh"}.)

  • Add the PyObject_GetOptionalAttr{.interpreted-text role="c:func"} and PyObject_GetOptionalAttrString{.interpreted-text role="c:func"} functions as alternatives to PyObject_GetAttr{.interpreted-text role="c:func"} and PyObject_GetAttrString{.interpreted-text role="c:func"} respectively. The new functions do not raise AttributeError{.interpreted-text role="exc"} if the requested attribute is not found on the object. These variants are more convenient and faster if the missing attribute should not be treated as a failure. (Contributed by Serhiy Storchaka in 106521{.interpreted-text role="gh"}.)

  • Add the PyErr_FormatUnraisable{.interpreted-text role="c:func"} function as an extension to PyErr_WriteUnraisable{.interpreted-text role="c:func"} that allows customizing the warning message. (Contributed by Serhiy Storchaka in 108082{.interpreted-text role="gh"}.)

  • Add new functions that return a strong reference{.interpreted-text role="term"} instead of a borrowed reference{.interpreted-text role="term"} for frame locals, globals, and builtins, as part of PEP 667 <whatsnew313-locals-semantics>{.interpreted-text role="ref"}:

    • PyEval_GetFrameBuiltins{.interpreted-text role="c:func"} replaces PyEval_GetBuiltins{.interpreted-text role="c:func"}
    • PyEval_GetFrameGlobals{.interpreted-text role="c:func"} replaces PyEval_GetGlobals{.interpreted-text role="c:func"}
    • PyEval_GetFrameLocals{.interpreted-text role="c:func"} replaces PyEval_GetLocals{.interpreted-text role="c:func"}

    (Contributed by Mark Shannon and Tian Gao in 74929{.interpreted-text role="gh"}.)

  • Add the Py_GetConstant{.interpreted-text role="c:func"} and Py_GetConstantBorrowed{.interpreted-text role="c:func"} functions to get strong <strong reference>{.interpreted-text role="term"} or borrowed <borrowed reference>{.interpreted-text role="term"} references to constants. For example, Py_GetConstant(Py_CONSTANT_ZERO) returns a strong reference to the constant zero. (Contributed by Victor Stinner in 115754{.interpreted-text role="gh"}.)

  • Add the PyImport_AddModuleRef{.interpreted-text role="c:func"} function as a replacement for PyImport_AddModule{.interpreted-text role="c:func"} that returns a strong reference{.interpreted-text role="term"} instead of a borrowed reference{.interpreted-text role="term"}. (Contributed by Victor Stinner in 105922{.interpreted-text role="gh"}.)

  • Add the Py_IsFinalizing{.interpreted-text role="c:func"} function to check whether the main Python interpreter is shutting down <interpreter shutdown>{.interpreted-text role="term"}. (Contributed by Victor Stinner in 108014{.interpreted-text role="gh"}.)

  • Add the PyList_GetItemRef{.interpreted-text role="c:func"} function as a replacement for PyList_GetItem{.interpreted-text role="c:func"} that returns a strong reference{.interpreted-text role="term"} instead of a borrowed reference{.interpreted-text role="term"}. (Contributed by Sam Gross in 114329{.interpreted-text role="gh"}.)

  • Add the PyList_Extend{.interpreted-text role="c:func"} and PyList_Clear{.interpreted-text role="c:func"} functions, mirroring the Python list.extend{.interpreted-text role="meth"} and list.clear{.interpreted-text role="meth"} methods. (Contributed by Victor Stinner in 111138{.interpreted-text role="gh"}.)

  • Add the PyLong_AsInt{.interpreted-text role="c:func"} function. It behaves similarly to PyLong_AsLong{.interpreted-text role="c:func"}, but stores the result in a C int{.interpreted-text role="c:expr"} instead of a C long{.interpreted-text role="c:expr"}. (Contributed by Victor Stinner in 108014{.interpreted-text role="gh"}.)

  • Add the PyLong_AsNativeBytes{.interpreted-text role="c:func"}, PyLong_FromNativeBytes{.interpreted-text role="c:func"}, and PyLong_FromUnsignedNativeBytes{.interpreted-text role="c:func"} functions to simplify converting between native integer types and Python int{.interpreted-text role="class"} objects. (Contributed by Steve Dower in 111140{.interpreted-text role="gh"}.)

  • Add PyModule_Add{.interpreted-text role="c:func"} function, which is similar to PyModule_AddObjectRef{.interpreted-text role="c:func"} and PyModule_AddObject{.interpreted-text role="c:func"}, but always steals a reference to the value. (Contributed by Serhiy Storchaka in 86493{.interpreted-text role="gh"}.)

  • Add the PyObject_GenericHash{.interpreted-text role="c:func"} function that implements the default hashing function of a Python object. (Contributed by Serhiy Storchaka in 113024{.interpreted-text role="gh"}.)

  • Add the Py_HashPointer{.interpreted-text role="c:func"} function to hash a raw pointer. (Contributed by Victor Stinner in 111545{.interpreted-text role="gh"}.)

  • Add the PyObject_VisitManagedDict{.interpreted-text role="c:func"} and PyObject_ClearManagedDict{.interpreted-text role="c:func"} functions. which must be called by the traverse and clear functions of a type using the Py_TPFLAGS_MANAGED_DICT{.interpreted-text role="c:macro"} flag. The pythoncapi-compat project can be used to use these functions with Python 3.11 and 3.12. (Contributed by Victor Stinner in 107073{.interpreted-text role="gh"}.)

  • Add the PyRefTracer_SetTracer{.interpreted-text role="c:func"} and PyRefTracer_GetTracer{.interpreted-text role="c:func"} functions, which enable tracking object creation and destruction in the same way that the tracemalloc{.interpreted-text role="mod"} module does. (Contributed by Pablo Galindo in 93502{.interpreted-text role="gh"}.)

  • Add the PySys_AuditTuple{.interpreted-text role="c:func"} function as an alternative to PySys_Audit{.interpreted-text role="c:func"} that takes event arguments as a Python tuple{.interpreted-text role="class"} object. (Contributed by Victor Stinner in 85283{.interpreted-text role="gh"}.)

  • Add the PyThreadState_GetUnchecked(){.interpreted-text role="c:func"} function as an alternative to PyThreadState_Get(){.interpreted-text role="c:func"} that doesn't kill the process with a fatal error if it is NULL. The caller is responsible for checking if the result is NULL. (Contributed by Victor Stinner in 108867{.interpreted-text role="gh"}.)

  • Add the PyType_GetFullyQualifiedName{.interpreted-text role="c:func"} function to get the type's fully qualified name. The module name is prepended if type.__module__{.interpreted-text role="attr"} is a string and is not equal to either 'builtins' or '__main__'. (Contributed by Victor Stinner in 111696{.interpreted-text role="gh"}.)

  • Add the PyType_GetModuleName{.interpreted-text role="c:func"} function to get the type's module name. This is equivalent to getting the type.__module__{.interpreted-text role="attr"} attribute. (Contributed by Eric Snow and Victor Stinner in 111696{.interpreted-text role="gh"}.)

  • Add the PyUnicode_EqualToUTF8AndSize{.interpreted-text role="c:func"} and PyUnicode_EqualToUTF8{.interpreted-text role="c:func"} functions to compare a Unicode object with a const char*{.interpreted-text role="c:expr"} UTF-8 encoded string and 1 if they are equal or 0 otherwise. These functions do not raise exceptions. (Contributed by Serhiy Storchaka in 110289{.interpreted-text role="gh"}.)

  • Add the PyWeakref_GetRef{.interpreted-text role="c:func"} function as an alternative to !PyWeakref_GetObject{.interpreted-text role="c:func"} that returns a strong reference{.interpreted-text role="term"} or NULL if the referent is no longer live. (Contributed by Victor Stinner in 105927{.interpreted-text role="gh"}.)

  • Add fixed variants of functions which silently ignore errors:

    • PyObject_HasAttrWithError{.interpreted-text role="c:func"} replaces PyObject_HasAttr{.interpreted-text role="c:func"}.
    • PyObject_HasAttrStringWithError{.interpreted-text role="c:func"} replaces PyObject_HasAttrString{.interpreted-text role="c:func"}.
    • PyMapping_HasKeyWithError{.interpreted-text role="c:func"} replaces PyMapping_HasKey{.interpreted-text role="c:func"}.
    • PyMapping_HasKeyStringWithError{.interpreted-text role="c:func"} replaces PyMapping_HasKeyString{.interpreted-text role="c:func"}.

    The new functions return -1 for errors and the standard 1 for true and 0 for false.

    (Contributed by Serhiy Storchaka in 108511{.interpreted-text role="gh"}.)

Changed C APIs

  • The keywords parameter of PyArg_ParseTupleAndKeywords{.interpreted-text role="c:func"} and PyArg_VaParseTupleAndKeywords{.interpreted-text role="c:func"} now has type char * const *{.interpreted-text role="c:expr"} in C and const char * const *{.interpreted-text role="c:expr"} in C++, instead of char **{.interpreted-text role="c:expr"}. In C++, this makes these functions compatible with arguments of type const char * const *{.interpreted-text role="c:expr"}, const char **{.interpreted-text role="c:expr"}, or char * const *{.interpreted-text role="c:expr"} without an explicit type cast. In C, the functions only support arguments of type char * const *{.interpreted-text role="c:expr"}. This can be overridden with the PY_CXX_CONST{.interpreted-text role="c:macro"} macro. (Contributed by Serhiy Storchaka in 65210{.interpreted-text role="gh"}.)

  • PyArg_ParseTupleAndKeywords{.interpreted-text role="c:func"} now supports non-ASCII keyword parameter names. (Contributed by Serhiy Storchaka in 110815{.interpreted-text role="gh"}.)

  • The !PyCode_GetFirstFree{.interpreted-text role="c:func"} function is now unstable API and is now named PyUnstable_Code_GetFirstFree{.interpreted-text role="c:func"}. (Contributed by Bogdan Romanyuk in 115781{.interpreted-text role="gh"}.)

  • The PyDict_GetItem{.interpreted-text role="c:func"}, PyDict_GetItemString{.interpreted-text role="c:func"}, PyMapping_HasKey{.interpreted-text role="c:func"}, PyMapping_HasKeyString{.interpreted-text role="c:func"}, PyObject_HasAttr{.interpreted-text role="c:func"}, PyObject_HasAttrString{.interpreted-text role="c:func"}, and PySys_GetObject{.interpreted-text role="c:func"} functions, each of which clears all errors which occurred when calling them now reports these errors using sys.unraisablehook{.interpreted-text role="func"}. You may replace them with other functions as recommended in the documentation. (Contributed by Serhiy Storchaka in 106672{.interpreted-text role="gh"}.)

  • Add support for the %T, %#T, %N and %#N formats to PyUnicode_FromFormat{.interpreted-text role="c:func"}:

    • %T: Get the fully qualified name of an object type
    • %#T: As above, but use a colon as the separator
    • %N: Get the fully qualified name of a type
    • %#N: As above, but use a colon as the separator

    See 737{.interpreted-text role="pep"} for more information. (Contributed by Victor Stinner in 111696{.interpreted-text role="gh"}.)

  • You no longer have to define the PY_SSIZE_T_CLEAN macro before including Python.h{.interpreted-text role="file"} when using # formats in format codes <arg-parsing-string-and-buffers>{.interpreted-text role="ref"}. APIs accepting the format codes always use Py_ssize_t for # formats. (Contributed by Inada Naoki in 104922{.interpreted-text role="gh"}.)

  • If Python is built in debug mode <debug-build>{.interpreted-text role="ref"} or with assertions <--with-assertions>{.interpreted-text role="option"}, PyTuple_SET_ITEM{.interpreted-text role="c:func"} and PyList_SET_ITEM{.interpreted-text role="c:func"} now check the index argument with an assertion. (Contributed by Victor Stinner in 106168{.interpreted-text role="gh"}.)

Limited C API Changes

  • The following functions are now included in the Limited C API:

    • PyMem_RawMalloc{.interpreted-text role="c:func"}
    • PyMem_RawCalloc{.interpreted-text role="c:func"}
    • PyMem_RawRealloc{.interpreted-text role="c:func"}
    • PyMem_RawFree{.interpreted-text role="c:func"}
    • PySys_Audit{.interpreted-text role="c:func"}
    • PySys_AuditTuple{.interpreted-text role="c:func"}
    • PyType_GetModuleByDef{.interpreted-text role="c:func"}

    (Contributed by Victor Stinner in 85283{.interpreted-text role="gh"} and 116936{.interpreted-text role="gh"}.)

  • Python built with --with-trace-refs{.interpreted-text role="option"} (tracing references) now supports the Limited API <limited-c-api>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in 108634{.interpreted-text role="gh"}.)

Removed C APIs

  • Remove several functions, macros, variables, etc with names prefixed by _Py or _PY (which are considered private). If your project is affected by one of these removals and you believe that the removed API should remain available, please open a new issue <using-the-tracker>{.interpreted-text role="ref"} to request a public C API and add cc: @vstinner to the issue to notify Victor Stinner. (Contributed by Victor Stinner in 106320{.interpreted-text role="gh"}.)

  • Remove old buffer protocols deprecated in Python 3.0. Use bufferobjects{.interpreted-text role="ref"} instead.

    • !PyObject_CheckReadBuffer{.interpreted-text role="c:func"}: Use PyObject_CheckBuffer{.interpreted-text role="c:func"} to test whether the object supports the buffer protocol. Note that PyObject_CheckBuffer{.interpreted-text role="c:func"} doesn't guarantee that PyObject_GetBuffer{.interpreted-text role="c:func"} will succeed. To test if the object is actually readable, see the next example of PyObject_GetBuffer{.interpreted-text role="c:func"}.

    • !PyObject_AsCharBuffer{.interpreted-text role="c:func"}, !PyObject_AsReadBuffer{.interpreted-text role="c:func"}: Use PyObject_GetBuffer{.interpreted-text role="c:func"} and PyBuffer_Release{.interpreted-text role="c:func"} instead:

      Py_buffer view;
      if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {
          return NULL;
      }
      // Use `view.buf` and `view.len` to read from the buffer.
      // You may need to cast buf as `(const char*)view.buf`.
      PyBuffer_Release(&view);
      
    • !PyObject_AsWriteBuffer{.interpreted-text role="c:func"}: Use PyObject_GetBuffer{.interpreted-text role="c:func"} and PyBuffer_Release{.interpreted-text role="c:func"} instead:

      Py_buffer view;
      if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) {
          return NULL;
      }
      // Use `view.buf` and `view.len` to write to the buffer.
      PyBuffer_Release(&view);
      

    (Contributed by Inada Naoki in 85275{.interpreted-text role="gh"}.)

  • Remove various functions deprecated in Python 3.9:

    • !PyEval_CallObject{.interpreted-text role="c:func"}, !PyEval_CallObjectWithKeywords{.interpreted-text role="c:func"}: Use PyObject_CallNoArgs{.interpreted-text role="c:func"} or PyObject_Call{.interpreted-text role="c:func"} instead.

      :::: warning ::: title Warning :::

      In PyObject_Call{.interpreted-text role="c:func"}, positional arguments must be a tuple{.interpreted-text role="class"} and must not be NULL, and keyword arguments must be a dict{.interpreted-text role="class"} or NULL, whereas the removed functions checked argument types and accepted NULL positional and keyword arguments. To replace PyEval_CallObjectWithKeywords(func, NULL, kwargs) with PyObject_Call{.interpreted-text role="c:func"}, pass an empty tuple as positional arguments using PyTuple_New(0) <PyTuple_New>{.interpreted-text role="c:func"}. ::::

    • !PyEval_CallFunction{.interpreted-text role="c:func"}: Use PyObject_CallFunction{.interpreted-text role="c:func"} instead.

    • !PyEval_CallMethod{.interpreted-text role="c:func"}: Use PyObject_CallMethod{.interpreted-text role="c:func"} instead.

    • !PyCFunction_Call{.interpreted-text role="c:func"}: Use PyObject_Call{.interpreted-text role="c:func"} instead.

    (Contributed by Victor Stinner in 105107{.interpreted-text role="gh"}.)

  • Remove the following old functions to configure the Python initialization, deprecated in Python 3.11:

    • !PySys_AddWarnOptionUnicode{.interpreted-text role="c:func"}: Use PyConfig.warnoptions{.interpreted-text role="c:member"} instead.
    • !PySys_AddWarnOption{.interpreted-text role="c:func"}: Use PyConfig.warnoptions{.interpreted-text role="c:member"} instead.
    • !PySys_AddXOption{.interpreted-text role="c:func"}: Use PyConfig.xoptions{.interpreted-text role="c:member"} instead.
    • !PySys_HasWarnOptions{.interpreted-text role="c:func"}: Use PyConfig.xoptions{.interpreted-text role="c:member"} instead.
    • !PySys_SetPath{.interpreted-text role="c:func"}: Set PyConfig.module_search_paths{.interpreted-text role="c:member"} instead.
    • !Py_SetPath{.interpreted-text role="c:func"}: Set PyConfig.module_search_paths{.interpreted-text role="c:member"} instead.
    • !Py_SetStandardStreamEncoding{.interpreted-text role="c:func"}: Set PyConfig.stdio_encoding{.interpreted-text role="c:member"} instead, and set also maybe PyConfig.legacy_windows_stdio{.interpreted-text role="c:member"} (on Windows).
    • !_Py_SetProgramFullPath{.interpreted-text role="c:func"}: Set PyConfig.executable{.interpreted-text role="c:member"} instead.

    Use the new PyConfig{.interpreted-text role="c:type"} API of the Python Initialization Configuration <init-config>{.interpreted-text role="ref"} instead (587{.interpreted-text role="pep"}), added to Python 3.8. (Contributed by Victor Stinner in 105145{.interpreted-text role="gh"}.)

  • Remove !PyEval_AcquireLock{.interpreted-text role="c:func"} and !PyEval_ReleaseLock{.interpreted-text role="c:func"} functions, deprecated in Python 3.2. They didn't update the current thread state. They can be replaced with:

    • PyEval_SaveThread{.interpreted-text role="c:func"} and PyEval_RestoreThread{.interpreted-text role="c:func"};
    • low-level PyEval_AcquireThread{.interpreted-text role="c:func"} and PyEval_RestoreThread{.interpreted-text role="c:func"};
    • or PyGILState_Ensure{.interpreted-text role="c:func"} and PyGILState_Release{.interpreted-text role="c:func"}.

    (Contributed by Victor Stinner in 105182{.interpreted-text role="gh"}.)

  • Remove the !PyEval_ThreadsInitialized{.interpreted-text role="c:func"} function, deprecated in Python 3.9. Since Python 3.7, !Py_Initialize{.interpreted-text role="c:func"} always creates the GIL: calling !PyEval_InitThreads{.interpreted-text role="c:func"} does nothing and !PyEval_ThreadsInitialized{.interpreted-text role="c:func"} always returns non-zero. (Contributed by Victor Stinner in 105182{.interpreted-text role="gh"}.)

  • Remove the !_PyInterpreterState_Get{.interpreted-text role="c:func"} alias to PyInterpreterState_Get(){.interpreted-text role="c:func"} which was kept for backward compatibility with Python 3.8. The pythoncapi-compat project can be used to get PyInterpreterState_Get(){.interpreted-text role="c:func"} on Python 3.8 and older. (Contributed by Victor Stinner in 106320{.interpreted-text role="gh"}.)

  • Remove the private !_PyObject_FastCall{.interpreted-text role="c:func"} function: use !PyObject_Vectorcall{.interpreted-text role="c:func"} which is available since Python 3.8 (590{.interpreted-text role="pep"}). (Contributed by Victor Stinner in 106023{.interpreted-text role="gh"}.)

  • Remove the cpython/pytime.h header file, which only contained private functions. (Contributed by Victor Stinner in 106316{.interpreted-text role="gh"}.)

  • Remove the undocumented PY_TIMEOUT_MAX constant from the limited C API. (Contributed by Victor Stinner in 110014{.interpreted-text role="gh"}.)

  • Remove the old trashcan macros Py_TRASHCAN_SAFE_BEGIN and Py_TRASHCAN_SAFE_END. Replace both with the new macros Py_TRASHCAN_BEGIN and Py_TRASHCAN_END. (Contributed by Irit Katriel in 105111{.interpreted-text role="gh"}.)

Deprecated C APIs

  • Deprecate old Python initialization functions:

    • !PySys_ResetWarnOptions{.interpreted-text role="c:func"}: Clear sys.warnoptions{.interpreted-text role="data"} and !warnings.filters{.interpreted-text role="data"} instead.
    • !Py_GetExecPrefix{.interpreted-text role="c:func"}: Get sys.exec_prefix{.interpreted-text role="data"} instead.
    • !Py_GetPath{.interpreted-text role="c:func"}: Get sys.path{.interpreted-text role="data"} instead.
    • !Py_GetPrefix{.interpreted-text role="c:func"}: Get sys.prefix{.interpreted-text role="data"} instead.
    • !Py_GetProgramFullPath{.interpreted-text role="c:func"}: Get sys.executable{.interpreted-text role="data"} instead.
    • !Py_GetProgramName{.interpreted-text role="c:func"}: Get sys.executable{.interpreted-text role="data"} instead.
    • !Py_GetPythonHome{.interpreted-text role="c:func"}: Get PyConfig.home{.interpreted-text role="c:member"} or the PYTHONHOME{.interpreted-text role="envvar"} environment variable instead.

    (Contributed by Victor Stinner in 105145{.interpreted-text role="gh"}.)

  • Soft deprecate <soft deprecated>{.interpreted-text role="term"} the PyEval_GetBuiltins{.interpreted-text role="c:func"}, PyEval_GetGlobals{.interpreted-text role="c:func"}, and PyEval_GetLocals{.interpreted-text role="c:func"} functions, which return a borrowed reference{.interpreted-text role="term"}. (Soft deprecated as part of 667{.interpreted-text role="pep"}.)

  • Deprecate the !PyImport_ImportModuleNoBlock{.interpreted-text role="c:func"} function, which is just an alias to PyImport_ImportModule{.interpreted-text role="c:func"} since Python 3.3. (Contributed by Victor Stinner in 105396{.interpreted-text role="gh"}.)

  • Soft deprecate <soft deprecated>{.interpreted-text role="term"} the PyModule_AddObject{.interpreted-text role="c:func"} function. It should be replaced with PyModule_Add{.interpreted-text role="c:func"} or PyModule_AddObjectRef{.interpreted-text role="c:func"}. (Contributed by Serhiy Storchaka in 86493{.interpreted-text role="gh"}.)

  • Deprecate the old Py_UNICODE and PY_UNICODE_TYPE types and the !Py_UNICODE_WIDE{.interpreted-text role="c:macro"} define. Use the wchar_t{.interpreted-text role="c:type"} type directly instead. Since Python 3.3, Py_UNICODE and PY_UNICODE_TYPE are just aliases to !wchar_t{.interpreted-text role="c:type"}. (Contributed by Victor Stinner in 105156{.interpreted-text role="gh"}.)

  • Deprecate the !PyWeakref_GetObject{.interpreted-text role="c:func"} and !PyWeakref_GET_OBJECT{.interpreted-text role="c:func"} functions, which return a borrowed reference{.interpreted-text role="term"}. Replace them with the new PyWeakref_GetRef{.interpreted-text role="c:func"} function, which returns a strong reference{.interpreted-text role="term"}. The pythoncapi-compat project can be used to get PyWeakref_GetRef{.interpreted-text role="c:func"} on Python 3.12 and older. (Contributed by Victor Stinner in 105927{.interpreted-text role="gh"}.)

Pending removal in Python 3.14

  • The ma_version_tag field in PyDictObject{.interpreted-text role="c:type"} for extension modules (699{.interpreted-text role="pep"}; 101193{.interpreted-text role="gh"}).
  • Creating immutable types <Py_TPFLAGS_IMMUTABLETYPE>{.interpreted-text role="c:data"} with mutable bases (95388{.interpreted-text role="gh"}).

Pending removal in Python 3.15

  • The !PyImport_ImportModuleNoBlock{.interpreted-text role="c:func"}: Use PyImport_ImportModule{.interpreted-text role="c:func"} instead.

  • !PyWeakref_GetObject{.interpreted-text role="c:func"} and !PyWeakref_GET_OBJECT{.interpreted-text role="c:func"}: Use PyWeakref_GetRef{.interpreted-text role="c:func"} instead. The pythoncapi-compat project can be used to get PyWeakref_GetRef{.interpreted-text role="c:func"} on Python 3.12 and older.

  • Py_UNICODE{.interpreted-text role="c:type"} type and the !Py_UNICODE_WIDE{.interpreted-text role="c:macro"} macro: Use wchar_t{.interpreted-text role="c:type"} instead.

  • !PyUnicode_AsDecodedObject{.interpreted-text role="c:func"}: Use PyCodec_Decode{.interpreted-text role="c:func"} instead.

  • !PyUnicode_AsDecodedUnicode{.interpreted-text role="c:func"}: Use PyCodec_Decode{.interpreted-text role="c:func"} instead; Note that some codecs (for example, "base64") may return a type other than str{.interpreted-text role="class"}, such as bytes{.interpreted-text role="class"}.

  • !PyUnicode_AsEncodedObject{.interpreted-text role="c:func"}: Use PyCodec_Encode{.interpreted-text role="c:func"} instead.

  • !PyUnicode_AsEncodedUnicode{.interpreted-text role="c:func"}: Use PyCodec_Encode{.interpreted-text role="c:func"} instead; Note that some codecs (for example, "base64") may return a type other than bytes{.interpreted-text role="class"}, such as str{.interpreted-text role="class"}.

  • Python initialization functions, deprecated in Python 3.13:

    • !Py_GetPath{.interpreted-text role="c:func"}: Use PyConfig_Get("module_search_paths") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.path{.interpreted-text role="data"}) instead.
    • !Py_GetPrefix{.interpreted-text role="c:func"}: Use PyConfig_Get("base_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.base_prefix{.interpreted-text role="data"}) instead. Use PyConfig_Get("prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.prefix{.interpreted-text role="data"}) if virtual environments <venv-def>{.interpreted-text role="ref"} need to be handled.
    • !Py_GetExecPrefix{.interpreted-text role="c:func"}: Use PyConfig_Get("base_exec_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.base_exec_prefix{.interpreted-text role="data"}) instead. Use PyConfig_Get("exec_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.exec_prefix{.interpreted-text role="data"}) if virtual environments <venv-def>{.interpreted-text role="ref"} need to be handled.
    • !Py_GetProgramFullPath{.interpreted-text role="c:func"}: Use PyConfig_Get("executable") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.executable{.interpreted-text role="data"}) instead.
    • !Py_GetProgramName{.interpreted-text role="c:func"}: Use PyConfig_Get("executable") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.executable{.interpreted-text role="data"}) instead.
    • !Py_GetPythonHome{.interpreted-text role="c:func"}: Use PyConfig_Get("home") <PyConfig_Get>{.interpreted-text role="c:func"} or the PYTHONHOME{.interpreted-text role="envvar"} environment variable instead.

    The pythoncapi-compat project can be used to get PyConfig_Get{.interpreted-text role="c:func"} on Python 3.13 and older.

  • Functions to configure Python's initialization, deprecated in Python 3.11:

    • !PySys_SetArgvEx(){.interpreted-text role="c:func"}: Set PyConfig.argv{.interpreted-text role="c:member"} instead.
    • !PySys_SetArgv(){.interpreted-text role="c:func"}: Set PyConfig.argv{.interpreted-text role="c:member"} instead.
    • !Py_SetProgramName(){.interpreted-text role="c:func"}: Set PyConfig.program_name{.interpreted-text role="c:member"} instead.
    • !Py_SetPythonHome(){.interpreted-text role="c:func"}: Set PyConfig.home{.interpreted-text role="c:member"} instead.
    • !PySys_ResetWarnOptions{.interpreted-text role="c:func"}: Clear sys.warnoptions{.interpreted-text role="data"} and !warnings.filters{.interpreted-text role="data"} instead.

    The Py_InitializeFromConfig{.interpreted-text role="c:func"} API should be used with PyConfig{.interpreted-text role="c:type"} instead.

  • Global configuration variables:

    • Py_DebugFlag{.interpreted-text role="c:var"}: Use PyConfig.parser_debug{.interpreted-text role="c:member"} or PyConfig_Get("parser_debug") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_VerboseFlag{.interpreted-text role="c:var"}: Use PyConfig.verbose{.interpreted-text role="c:member"} or PyConfig_Get("verbose") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_QuietFlag{.interpreted-text role="c:var"}: Use PyConfig.quiet{.interpreted-text role="c:member"} or PyConfig_Get("quiet") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_InteractiveFlag{.interpreted-text role="c:var"}: Use PyConfig.interactive{.interpreted-text role="c:member"} or PyConfig_Get("interactive") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_InspectFlag{.interpreted-text role="c:var"}: Use PyConfig.inspect{.interpreted-text role="c:member"} or PyConfig_Get("inspect") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_OptimizeFlag{.interpreted-text role="c:var"}: Use PyConfig.optimization_level{.interpreted-text role="c:member"} or PyConfig_Get("optimization_level") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_NoSiteFlag{.interpreted-text role="c:var"}: Use PyConfig.site_import{.interpreted-text role="c:member"} or PyConfig_Get("site_import") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_BytesWarningFlag{.interpreted-text role="c:var"}: Use PyConfig.bytes_warning{.interpreted-text role="c:member"} or PyConfig_Get("bytes_warning") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_FrozenFlag{.interpreted-text role="c:var"}: Use PyConfig.pathconfig_warnings{.interpreted-text role="c:member"} or PyConfig_Get("pathconfig_warnings") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_IgnoreEnvironmentFlag{.interpreted-text role="c:var"}: Use PyConfig.use_environment{.interpreted-text role="c:member"} or PyConfig_Get("use_environment") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_DontWriteBytecodeFlag{.interpreted-text role="c:var"}: Use PyConfig.write_bytecode{.interpreted-text role="c:member"} or PyConfig_Get("write_bytecode") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_NoUserSiteDirectory{.interpreted-text role="c:var"}: Use PyConfig.user_site_directory{.interpreted-text role="c:member"} or PyConfig_Get("user_site_directory") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_UnbufferedStdioFlag{.interpreted-text role="c:var"}: Use PyConfig.buffered_stdio{.interpreted-text role="c:member"} or PyConfig_Get("buffered_stdio") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_HashRandomizationFlag{.interpreted-text role="c:var"}: Use PyConfig.use_hash_seed{.interpreted-text role="c:member"} and PyConfig.hash_seed{.interpreted-text role="c:member"} or PyConfig_Get("hash_seed") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_IsolatedFlag{.interpreted-text role="c:var"}: Use PyConfig.isolated{.interpreted-text role="c:member"} or PyConfig_Get("isolated") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_LegacyWindowsFSEncodingFlag{.interpreted-text role="c:var"}: Use PyPreConfig.legacy_windows_fs_encoding{.interpreted-text role="c:member"} or PyConfig_Get("legacy_windows_fs_encoding") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • Py_LegacyWindowsStdioFlag{.interpreted-text role="c:var"}: Use PyConfig.legacy_windows_stdio{.interpreted-text role="c:member"} or PyConfig_Get("legacy_windows_stdio") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • !Py_FileSystemDefaultEncoding{.interpreted-text role="c:var"}, !Py_HasFileSystemDefaultEncoding{.interpreted-text role="c:var"}: Use PyConfig.filesystem_encoding{.interpreted-text role="c:member"} or PyConfig_Get("filesystem_encoding") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • !Py_FileSystemDefaultEncodeErrors{.interpreted-text role="c:var"}: Use PyConfig.filesystem_errors{.interpreted-text role="c:member"} or PyConfig_Get("filesystem_errors") <PyConfig_Get>{.interpreted-text role="c:func"} instead.
    • !Py_UTF8Mode{.interpreted-text role="c:var"}: Use PyPreConfig.utf8_mode{.interpreted-text role="c:member"} or PyConfig_Get("utf8_mode") <PyConfig_Get>{.interpreted-text role="c:func"} instead. (see Py_PreInitialize{.interpreted-text role="c:func"})

    The Py_InitializeFromConfig{.interpreted-text role="c:func"} API should be used with PyConfig{.interpreted-text role="c:type"} to set these options. Or PyConfig_Get{.interpreted-text role="c:func"} can be used to get these options at runtime.

Pending removal in Python 3.16

  • The bundled copy of libmpdec.

Pending removal in Python 3.18

  • The following private functions are deprecated and planned for removal in Python 3.18:

    • !_PyBytes_Join{.interpreted-text role="c:func"}: use PyBytes_Join{.interpreted-text role="c:func"}.
    • !_PyDict_GetItemStringWithError{.interpreted-text role="c:func"}: use PyDict_GetItemStringRef{.interpreted-text role="c:func"}.
    • !_PyDict_Pop(){.interpreted-text role="c:func"}: use PyDict_Pop{.interpreted-text role="c:func"}.
    • !_PyLong_Sign(){.interpreted-text role="c:func"}: use PyLong_GetSign{.interpreted-text role="c:func"}.
    • !_PyLong_FromDigits{.interpreted-text role="c:func"} and !_PyLong_New{.interpreted-text role="c:func"}: use PyLongWriter_Create{.interpreted-text role="c:func"}.
    • !_PyThreadState_UncheckedGet{.interpreted-text role="c:func"}: use PyThreadState_GetUnchecked{.interpreted-text role="c:func"}.
    • !_PyUnicode_AsString{.interpreted-text role="c:func"}: use PyUnicode_AsUTF8{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_Init{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_Init(&writer) with writer = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_Finish{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_Finish(&writer) with PyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_Dealloc{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_Dealloc(&writer) with PyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_WriteChar{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_WriteChar(&writer, ch) with PyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_WriteStr{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_WriteStr(&writer, str) with PyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_WriteSubstring{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_WriteSubstring(&writer, str, start, end) with PyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_WriteASCIIString{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_WriteASCIIString(&writer, str) with PyUnicodeWriter_WriteASCII(writer, str) <PyUnicodeWriter_WriteASCII>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_WriteLatin1String{.interpreted-text role="c:func"}: replace _PyUnicodeWriter_WriteLatin1String(&writer, str) with PyUnicodeWriter_WriteUTF8(writer, str) <PyUnicodeWriter_WriteUTF8>{.interpreted-text role="c:func"}.
    • !_PyUnicodeWriter_Prepare{.interpreted-text role="c:func"}: (no replacement).
    • !_PyUnicodeWriter_PrepareKind{.interpreted-text role="c:func"}: (no replacement).
    • !_Py_HashPointer{.interpreted-text role="c:func"}: use Py_HashPointer{.interpreted-text role="c:func"}.
    • !_Py_fopen_obj{.interpreted-text role="c:func"}: use Py_fopen{.interpreted-text role="c:func"}.

    The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older. (Contributed by Victor Stinner in 128863{.interpreted-text role="gh"}.)

Pending removal in future versions

The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.

  • Py_TPFLAGS_HAVE_FINALIZE{.interpreted-text role="c:macro"}: Unneeded since Python 3.8.
  • PyErr_Fetch{.interpreted-text role="c:func"}: Use PyErr_GetRaisedException{.interpreted-text role="c:func"} instead.
  • PyErr_NormalizeException{.interpreted-text role="c:func"}: Use PyErr_GetRaisedException{.interpreted-text role="c:func"} instead.
  • PyErr_Restore{.interpreted-text role="c:func"}: Use PyErr_SetRaisedException{.interpreted-text role="c:func"} instead.
  • PyModule_GetFilename{.interpreted-text role="c:func"}: Use PyModule_GetFilenameObject{.interpreted-text role="c:func"} instead.
  • PyOS_AfterFork{.interpreted-text role="c:func"}: Use PyOS_AfterFork_Child{.interpreted-text role="c:func"} instead.
  • PySlice_GetIndicesEx{.interpreted-text role="c:func"}: Use PySlice_Unpack{.interpreted-text role="c:func"} and PySlice_AdjustIndices{.interpreted-text role="c:func"} instead.
  • PyUnicode_READY{.interpreted-text role="c:func"}: Unneeded since Python 3.12
  • !PyErr_Display{.interpreted-text role="c:func"}: Use PyErr_DisplayException{.interpreted-text role="c:func"} instead.
  • !_PyErr_ChainExceptions{.interpreted-text role="c:func"}: Use !_PyErr_ChainExceptions1{.interpreted-text role="c:func"} instead.
  • !PyBytesObject.ob_shash{.interpreted-text role="c:member"} member: call PyObject_Hash{.interpreted-text role="c:func"} instead.
  • Thread Local Storage (TLS) API:
    • PyThread_create_key{.interpreted-text role="c:func"}: Use PyThread_tss_alloc{.interpreted-text role="c:func"} instead.
    • PyThread_delete_key{.interpreted-text role="c:func"}: Use PyThread_tss_free{.interpreted-text role="c:func"} instead.
    • PyThread_set_key_value{.interpreted-text role="c:func"}: Use PyThread_tss_set{.interpreted-text role="c:func"} instead.
    • PyThread_get_key_value{.interpreted-text role="c:func"}: Use PyThread_tss_get{.interpreted-text role="c:func"} instead.
    • PyThread_delete_key_value{.interpreted-text role="c:func"}: Use PyThread_tss_delete{.interpreted-text role="c:func"} instead.
    • PyThread_ReInitTLS{.interpreted-text role="c:func"}: Unneeded since Python 3.7.

Build Changes

  • arm64-apple-ios and arm64-apple-ios-simulator are both now 11{.interpreted-text role="pep"} tier 3 platforms. (PEP 730 <whatsnew313-platform-support>{.interpreted-text role="ref"} written and implementation contributed by Russell Keith-Magee in 114099{.interpreted-text role="gh"}.)
  • aarch64-linux-android and x86_64-linux-android are both now 11{.interpreted-text role="pep"} tier 3 platforms. (PEP 738 <whatsnew313-platform-support>{.interpreted-text role="ref"} written and implementation contributed by Malcolm Smith in 116622{.interpreted-text role="gh"}.)
  • wasm32-wasi is now a 11{.interpreted-text role="pep"} tier 2 platform. (Contributed by Brett Cannon in 115192{.interpreted-text role="gh"}.)
  • wasm32-emscripten is no longer a 11{.interpreted-text role="pep"} supported platform. (Contributed by Brett Cannon in 115192{.interpreted-text role="gh"}.)
  • Building CPython now requires a compiler with support for the C11 atomic library, GCC built-in atomic functions, or MSVC interlocked intrinsics.
  • Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate the configure{.interpreted-text role="file"} script. (Contributed by Christian Heimes in 89886{.interpreted-text role="gh"} and by Victor Stinner in 112090{.interpreted-text role="gh"}.)
  • SQLite 3.15.2 or newer is required to build the sqlite3{.interpreted-text role="mod"} extension module. (Contributed by Erlend Aasland in 105875{.interpreted-text role="gh"}.)
  • CPython now bundles the mimalloc library by default. It is licensed under the MIT license; see mimalloc license <mimalloc-license>{.interpreted-text role="ref"}. The bundled mimalloc has custom changes, see 113141{.interpreted-text role="gh"} for details. (Contributed by Dino Viehland in 109914{.interpreted-text role="gh"}.)
  • The configure{.interpreted-text role="file"} option --with-system-libmpdec{.interpreted-text role="option"} now defaults to yes. The bundled copy of libmpdec will be removed in Python 3.16.
  • Python built with configure{.interpreted-text role="file"} --with-trace-refs{.interpreted-text role="option"} (tracing references) is now ABI compatible with the Python release build and debug build <debug-build>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in 108634{.interpreted-text role="gh"}.)
  • On POSIX systems, the pkg-config (.pc) filenames now include the ABI flags. For example, the free-threaded build generates python-3.13t.pc and the debug build generates python-3.13d.pc.
  • The errno, fcntl, grp, md5, pwd, resource, termios, winsound, _ctypes_test, _multiprocessing.posixshmem, _scproxy, _stat, _statistics, _testconsole, _testimportmultiple and _uuid C extensions are now built with the limited C API <limited-c-api>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in 85283{.interpreted-text role="gh"}.)

Porting to Python 3.13

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in the Python API

::: {#pep667-porting-notes-py}

  • PEP 667 <whatsnew313-locals-semantics>{.interpreted-text role="ref"} introduces several changes to the semantics of locals{.interpreted-text role="func"} and f_locals <frame.f_locals>{.interpreted-text role="attr"}:

    • Calling locals{.interpreted-text role="func"} in an optimized scope{.interpreted-text role="term"} now produces an independent snapshot on each call, and hence no longer implicitly updates previously returned references. Obtaining the legacy CPython behavior now requires explicit calls to update the initially returned dictionary with the results of subsequent calls to !locals{.interpreted-text role="func"}. Code execution functions that implicitly target !locals{.interpreted-text role="func"} (such as exec and eval) must be passed an explicit namespace to access their results in an optimized scope. (Changed as part of 667{.interpreted-text role="pep"}.)
    • Calling locals{.interpreted-text role="func"} from a comprehension at module or class scope (including via exec or eval) once more behaves as if the comprehension were running as an independent nested function (i.e. the local variables from the containing scope are not included). In Python 3.12, this had changed to include the local variables from the containing scope when implementing 709{.interpreted-text role="pep"}. (Changed as part of 667{.interpreted-text role="pep"}.)
    • Accessing FrameType.f_locals <frame.f_locals>{.interpreted-text role="attr"} in an optimized scope{.interpreted-text role="term"} now returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly with dict or the proxy's .copy() method. (Changed as part of 667{.interpreted-text role="pep"}.)
  • functools.partial{.interpreted-text role="class"} now emits a FutureWarning{.interpreted-text role="exc"} when used as a method. The behavior will change in future Python versions. Wrap it in staticmethod{.interpreted-text role="func"} if you want to preserve the old behavior. (Contributed by Serhiy Storchaka in 121027{.interpreted-text role="gh"}.)

  • An OSError{.interpreted-text role="exc"} is now raised by getpass.getuser{.interpreted-text role="func"} for any failure to retrieve a username, instead of ImportError{.interpreted-text role="exc"} on non-Unix platforms or KeyError{.interpreted-text role="exc"} on Unix platforms where the password database is empty.

  • The value of the !mode{.interpreted-text role="attr"} attribute of gzip.GzipFile{.interpreted-text role="class"} is now a string ('rb' or 'wb') instead of an integer (1 or 2). The value of the !mode{.interpreted-text role="attr"} attribute of the readable file-like object returned by zipfile.ZipFile.open{.interpreted-text role="meth"} is now 'rb' instead of 'r'. (Contributed by Serhiy Storchaka in 115961{.interpreted-text role="gh"}.)

  • mailbox.Maildir{.interpreted-text role="class"} now ignores files with a leading dot (.). (Contributed by Zackery Spytz in 65559{.interpreted-text role="gh"}.)

  • pathlib.Path.glob{.interpreted-text role="meth"} and ~pathlib.Path.rglob{.interpreted-text role="meth"} now return both files and directories if a pattern that ends with "**" is given, rather than directories only. Add a trailing slash to keep the previous behavior and only match directories.

  • The threading{.interpreted-text role="mod"} module now expects the !_thread{.interpreted-text role="mod"} module to have an !_is_main_interpreter{.interpreted-text role="func"} function. This function takes no arguments and returns True if the current interpreter is the main interpreter.

    Any library or application that provides a custom !_thread{.interpreted-text role="mod"} module must provide !_is_main_interpreter{.interpreted-text role="func"}, just like the module's other "private" attributes. (112826{.interpreted-text role="gh"}.)

:::

Changes in the C API

  • Python.h no longer includes the <ieeefp.h> standard header. It was included for the !finite{.interpreted-text role="c:func"} function which is now provided by the <math.h> header. It should now be included explicitly if needed. Remove also the HAVE_IEEEFP_H macro. (Contributed by Victor Stinner in 108765{.interpreted-text role="gh"}.)

  • Python.h no longer includes these standard header files: <time.h>, <sys/select.h> and <sys/time.h>. If needed, they should now be included explicitly. For example, <time.h> provides the !clock{.interpreted-text role="c:func"} and !gmtime{.interpreted-text role="c:func"} functions, <sys/select.h> provides the !select{.interpreted-text role="c:func"} function, and <sys/time.h> provides the !futimes{.interpreted-text role="c:func"}, !gettimeofday{.interpreted-text role="c:func"} and !setitimer{.interpreted-text role="c:func"} functions. (Contributed by Victor Stinner in 108765{.interpreted-text role="gh"}.)

  • On Windows, Python.h no longer includes the <stddef.h> standard header file. If needed, it should now be included explicitly. For example, it provides !offsetof{.interpreted-text role="c:func"} function, and size_t and ptrdiff_t types. Including <stddef.h> explicitly was already needed by all other platforms, the HAVE_STDDEF_H macro is only defined on Windows. (Contributed by Victor Stinner in 108765{.interpreted-text role="gh"}.)

  • If the Py_LIMITED_API{.interpreted-text role="c:macro"} macro is defined, !Py_BUILD_CORE{.interpreted-text role="c:macro"}, !Py_BUILD_CORE_BUILTIN{.interpreted-text role="c:macro"} and !Py_BUILD_CORE_MODULE{.interpreted-text role="c:macro"} macros are now undefined by <Python.h>. (Contributed by Victor Stinner in 85283{.interpreted-text role="gh"}.)

  • The old trashcan macros Py_TRASHCAN_SAFE_BEGIN and Py_TRASHCAN_SAFE_END were removed. They should be replaced by the new macros Py_TRASHCAN_BEGIN and Py_TRASHCAN_END.

    A tp_dealloc function that has the old macros, such as:

    static void
    mytype_dealloc(mytype *p)
    {
        PyObject_GC_UnTrack(p);
        Py_TRASHCAN_SAFE_BEGIN(p);
        ...
        Py_TRASHCAN_SAFE_END
    }
    

    should migrate to the new macros as follows:

    static void
    mytype_dealloc(mytype *p)
    {
        PyObject_GC_UnTrack(p);
        Py_TRASHCAN_BEGIN(p, mytype_dealloc)
        ...
        Py_TRASHCAN_END
    }
    

    Note that Py_TRASHCAN_BEGIN has a second argument which should be the deallocation function it is in. The new macros were added in Python 3.8 and the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel in 105111{.interpreted-text role="gh"}.)

::: {#pep667-porting-notes-c}

  • PEP 667 <whatsnew313-locals-semantics>{.interpreted-text role="ref"} introduces several changes to frame-related functions:

    • The effects of mutating the dictionary returned from PyEval_GetLocals{.interpreted-text role="c:func"} in an optimized scope{.interpreted-text role="term"} have changed. New dict entries added this way will now only be visible to subsequent PyEval_GetLocals{.interpreted-text role="c:func"} calls in that frame, as PyFrame_GetLocals{.interpreted-text role="c:func"}, locals{.interpreted-text role="func"}, and FrameType.f_locals <frame.f_locals>{.interpreted-text role="attr"} no longer access the same underlying cached dictionary. Changes made to entries for actual variable names and names added via the write-through proxy interfaces will be overwritten on subsequent calls to PyEval_GetLocals{.interpreted-text role="c:func"} in that frame. The recommended code update depends on how the function was being used, so refer to the deprecation notice on the function for details.
    • Calling PyFrame_GetLocals{.interpreted-text role="c:func"} in an optimized scope{.interpreted-text role="term"} now returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly (e.g. with PyDict_Copy{.interpreted-text role="c:func"}), or by calling the new PyEval_GetFrameLocals{.interpreted-text role="c:func"} API.
    • !PyFrame_FastToLocals{.interpreted-text role="c:func"} and !PyFrame_FastToLocalsWithError{.interpreted-text role="c:func"} no longer have any effect. Calling these functions has been redundant since Python 3.11, when PyFrame_GetLocals{.interpreted-text role="c:func"} was first introduced.
    • !PyFrame_LocalsToFast{.interpreted-text role="c:func"} no longer has any effect. Calling this function is redundant now that PyFrame_GetLocals{.interpreted-text role="c:func"} returns a write-through proxy for optimized scopes <optimized scope>{.interpreted-text role="term"}.
  • Python 3.13 removed many private functions. Some of them can be replaced using these alternatives:

    • _PyDict_Pop(): PyDict_Pop{.interpreted-text role="c:func"} or PyDict_PopString{.interpreted-text role="c:func"};
    • _PyDict_GetItemWithError(): PyDict_GetItemRef{.interpreted-text role="c:func"};
    • _PyErr_WriteUnraisableMsg(): PyErr_FormatUnraisable{.interpreted-text role="c:func"};
    • _PyEval_SetTrace(): PyEval_SetTrace{.interpreted-text role="c:func"} or PyEval_SetTraceAllThreads{.interpreted-text role="c:func"};
    • _PyList_Extend(): PyList_Extend{.interpreted-text role="c:func"};
    • _PyLong_AsInt(): PyLong_AsInt{.interpreted-text role="c:func"};
    • _PyMem_RawStrdup(): strdup();
    • _PyMem_Strdup(): strdup();
    • _PyObject_ClearManagedDict(): PyObject_ClearManagedDict{.interpreted-text role="c:func"};
    • _PyObject_VisitManagedDict(): PyObject_VisitManagedDict{.interpreted-text role="c:func"};
    • _PyThreadState_UncheckedGet(): PyThreadState_GetUnchecked(){.interpreted-text role="c:func"};
    • _PyTime_AsSecondsDouble(): PyTime_AsSecondsDouble{.interpreted-text role="c:func"};
    • _PyTime_GetMonotonicClock(): PyTime_Monotonic{.interpreted-text role="c:func"} or PyTime_MonotonicRaw{.interpreted-text role="c:func"};
    • _PyTime_GetPerfCounter(): PyTime_PerfCounter{.interpreted-text role="c:func"} or PyTime_PerfCounterRaw{.interpreted-text role="c:func"};
    • _PyTime_GetSystemClock(): PyTime_Time{.interpreted-text role="c:func"} or PyTime_TimeRaw{.interpreted-text role="c:func"};
    • _PyTime_MAX: PyTime_MAX{.interpreted-text role="c:var"};
    • _PyTime_MIN: PyTime_MIN{.interpreted-text role="c:var"};
    • _PyTime_t: PyTime_t{.interpreted-text role="c:type"};
    • _Py_HashPointer(): Py_HashPointer{.interpreted-text role="c:func"};
    • _Py_IsFinalizing(): Py_IsFinalizing{.interpreted-text role="c:func"}.

    The pythoncapi-compat project can be used to get most of these new functions on Python 3.12 and older.

:::

Regression Test Changes

  • Python built with configure{.interpreted-text role="file"} --with-pydebug{.interpreted-text role="option"} now supports a -X presite=package.module <-X>{.interpreted-text role="option"} command-line option. If used, it specifies a module that should be imported early in the lifecycle of the interpreter, before site.py is executed. (Contributed by Łukasz Langa in 110769{.interpreted-text role="gh"}.)