Spaces:
Running on Zero
A newer version of the Gradio SDK is available: 6.22.0
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"} andimproved error messages <whatsnew313-improved-error-messages>{.interpreted-text role="ref"}. 667{.interpreted-text role="pep"}: Thelocals{.interpreted-text role="func"} builtin now hasdefined 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 theglobal interpreter lock{.interpreted-text role="term"} disabled. SeeFree-threaded CPython <whatsnew313-free-threaded-cpython>{.interpreted-text role="ref"} for more details.744{.interpreted-text role="pep"}: A basicJIT 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 intracebacks <whatsnew313-improved-error-messages>{.interpreted-text role="ref"} anddoctest <whatsnew313-doctest>{.interpreted-text role="ref"} output. This can be disabled through thePYTHON_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 throughself.Xin 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 duringfinalization <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"} andbase64.z85decode{.interpreted-text role="func"} support encoding and decoding Z85 data. - The
copy{.interpreted-text role="mod"} module now has acopy.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 defaultdbm{.interpreted-text role="mod"} backend. - The
os{.interpreted-text role="mod"} module has asuite 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 acommand-line interface <random-cli>{.interpreted-text role="ref"}.
Security improvements:
ssl.create_default_context{.interpreted-text role="func"} setsssl.VERIFY_X509_PARTIAL_CHAIN{.interpreted-text role="data"} andssl.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 theGIL{.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 generating669{.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"}, andtyping.TypeVarTuple{.interpreted-text role="data"}) now support defaults.702{.interpreted-text role="pep"}: The newwarnings.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 atyping.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 totyping.TypeGuard{.interpreted-text role="data"}.
Platform support:
730{.interpreted-text role="pep"}: Apple's iOS is now anofficially supported platform <whatsnew313-platform-support>{.interpreted-text role="ref"}, attier 3 <11#tier-3>{.interpreted-text role="pep"}.738{.interpreted-text role="pep"}: Android is now anofficially supported platform <whatsnew313-platform-support>{.interpreted-text role="ref"}, attier 3 <11#tier-3>{.interpreted-text role="pep"}.wasm32-wasiis now supported as atier 2 <11#tier-2>{.interpreted-text role="pep"} platform.wasm32-emscriptenis 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"}, andquit{.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 (pressF3{.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 newPYTHON_COLORS{.interpreted-text role="envvar"} environment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. (Contributed by Pablo Galindo Salgado in112730{.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 variablePYTHON_JIT=0.yes-off: Build the JIT but disable it by default. To enable the JIT at runtime, pass the environment variablePYTHON_JIT=1.interpreter: Enable the Tier 2 interpreter but disable the JIT. The interpreter can be disabled by running withPYTHON_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.pycfiles), 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 asdoctest{.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"} and118160{.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 formfrom .__future__ import ...are now simply standard relative imports, with no special features activated. (Contributed by Jeremiah Gabriel Pascual in118216{.interpreted-text role="gh"}.)global{.interpreted-text role="keyword"} declarations are now permitted inexcept{.interpreted-text role="keyword"} blocks when that global is used in theelse{.interpreted-text role="keyword"} block. Previously this raised an erroneousSyntaxError{.interpreted-text role="exc"}. (Contributed by Irit Katriel in111123{.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 in111374{.interpreted-text role="gh"}.)Add
support for the perf profiler <perf_profiling>{.interpreted-text role="ref"} working without frame pointers through the new environment variablePYTHON_PERF_JIT_SUPPORT{.interpreted-text role="envvar"} and command-line option-X perf_jit <-X>{.interpreted-text role="option"}. (Contributed by Pablo Galindo in118518{.interpreted-text role="gh"}.)The location of a
.python_history{.interpreted-text role="file"} file can be changed via the newPYTHON_HISTORY{.interpreted-text role="envvar"} environment variable. (Contributed by Levi Sabah, Zackery Spytz and Hugo van Kemenade in73965{.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 throughself.<name>from any function in its body. (Contributed by Irit Katriel in115775{.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 in118465{.interpreted-text role="gh"}.)The
exec{.interpreted-text role="func"} andeval{.interpreted-text role="func"} builtins now accept the globals and locals arguments as keywords. (Contributed by Raphael Gaschignard in105879{.interpreted-text role="gh"})The
compile{.interpreted-text role="func"} builtin now accepts a new flag,ast.PyCF_OPTIMIZED_AST, which is similar toast.PyCF_ONLY_ASTexcept that the returned AST is optimized according to the value of the optimize argument. (Contributed by Irit Katriel in108113{.interpreted-text role="gh"}).Add a
~property.__name__{.interpreted-text role="attr"} attribute onproperty{.interpreted-text role="class"} objects. (Contributed by Eugene Toder in101860{.interpreted-text role="gh"}.)Add
PythonFinalizationError{.interpreted-text role="exc"}, a new exception derived fromRuntimeError{.interpreted-text role="exc"} and used to signal when operations are blocked duringfinalization <interpreter shutdown>{.interpreted-text role="term"}. The following callables now raise!PythonFinalizationError{.interpreted-text role="exc"}, instead ofRuntimeError{.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 in106487{.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 thebz2{.interpreted-text role="mod"},lzma{.interpreted-text role="mod"},tarfile{.interpreted-text role="mod"}, andzipfile{.interpreted-text role="mod"} modules. (Contributed by Serhiy Storchaka in115961{.interpreted-text role="gh"}.)
New Modules
dbm.sqlite3{.interpreted-text role="mod"}: An SQLite backend fordbm{.interpreted-text role="mod"}. (Contributed by Raymond Hettinger and Erlend E. Aasland in100414{.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 in83648{.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 in80480{.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 in114894{.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 toLoad() <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"}, and118851{.interpreted-text role="gh"}.)ast.parse{.interpreted-text role="func"} now accepts an optional argument optimize which is passed on tocompile{.interpreted-text role="func"}. This makes it possible to obtain an optimized AST. (Contributed by Irit Katriel in108113{.interpreted-text role="gh"}.)
asyncio
asyncio.as_completed{.interpreted-text role="func"} now returns an object that is both anasynchronous iterator{.interpreted-text role="term"} and a plainiterator{.interpreted-text role="term"} ofawaitables <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 in77714{.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 in111246{.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 in115199{.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 in104228{.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 in113538{.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 in81322{.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 nextawait{.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_cancelflag 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 aRuntimeWarning{.interpreted-text role="exc"} about the given coroutine being never awaited). (Contributed by Arthur Tacca and Jason Zhang in115957{.interpreted-text role="gh"}.)The function and methods named
create_taskhave received a new**kwargsargument 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**kwargsargument 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 in128307{.interpreted-text role="gh"}.)
base64
- Add
~base64.z85encode{.interpreted-text role="func"} and~base64.z85decode{.interpreted-text role="func"} functions for encodingbytes{.interpreted-text role="class"} as Z85 data and decoding Z85-encoded data to!bytes{.interpreted-text role="class"}. (Contributed by Matan Perelman in75299{.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 ofos.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in109649{.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 ofos.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in109649{.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 in66449{.interpreted-text role="gh"}.)
copy
The new
~copy.replace{.interpreted-text role="func"} function and thereplace 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 in108751{.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 callingsuper().__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.- Custom logic that was done in
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 in112433{.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 in100414{.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 in107122{.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 in112137{.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 in112962{.interpreted-text role="gh"}.)
doctest {#whatsnew313-doctest}
doctest{.interpreted-text role="mod"} output is now colored by default. This can be controlled via the newPYTHON_COLORS{.interpreted-text role="envvar"} environment variable as well as the canonical |NO_COLOR| and |FORCE_COLOR| environment variables. See alsousing-on-controlling-color{.interpreted-text role="ref"}. (Contributed by Hugo van Kemenade in117225{.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 in108794{.interpreted-text role="gh"}.)
- 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 in121650{.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 (defaultTrue). To get the old behavior (accepting malformed input), usestrict=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 for102988{.interpreted-text role="gh"} to improve the2023-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 standardformat specification mini-language <formatspec>{.interpreted-text role="ref"} rules for fill, alignment, sign handling, minimum width, and grouping. (Contributed by Mark Dickinson in111320{.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 in72904{.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 in116608{.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 withsys.unraisablehook{.interpreted-text role="data"}. Previously, errors were ignored silently by default, and only logged inPython Development Mode <devmode>{.interpreted-text role="ref"} or when using aPython debug build <debug-build>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in62948{.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 in109466{.interpreted-text role="gh"}.) - Fix
is_globalandis_privatebehavior 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 in113171{.interpreted-text role="gh"}.)
itertools
~itertools.batched{.interpreted-text role="func"} has a new strict parameter, which raises aValueError{.interpreted-text role="exc"} if the final batch is shorter than the specified batch size. (Contributed by Raymond Hettinger in113202{.interpreted-text role="gh"}.)
marshal
- Add the allow_code parameter in module functions. Passing
allow_code=Falseprevents serialization and de-serialization of code objects which are incompatible between Python versions. (Contributed by Serhiy Storchaka in113626{.interpreted-text role="gh"}.)
math
- The new function
~math.fma{.interpreted-text role="func"} performs fused multiply-add operations. This computesx * y + zwith only a single round, and so avoids any intermediate loss of precision. It wraps thefma()function provided by C99, and follows the specification of the IEEE 754 "fusedMultiplyAdd" operation for special cases. (Contributed by Mark Dickinson and Victor Stinner in73468{.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 nowsoft deprecated{.interpreted-text role="term"}. (Contributed by Serhiy Storchaka in66543{.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 in118209{.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 in111835{.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 in78502{.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 ofos.cpu_count{.interpreted-text role="func"}. (Contributed by Victor Stinner in109649{.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 in109649{.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 variablePYTHON_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 in109595{.interpreted-text role="gh"}.)- Add a
low level interface <os-timerfd>{.interpreted-text role="ref"} to Linux'stimer 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 in108277{.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"} isFalseon Windows. (Contributed by Serhiy Storchaka in59616{.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 in113191{.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 of0o700to apply access control to the new directory. This implicitly affectstempfile.mkdtemp{.interpreted-text role="func"} and is a mitigation for2024-4030{.interpreted-text role="cve"}. Other values for mode continue to be ignored. (Contributed by Steve Dower in118486{.interpreted-text role="gh"}.) ~os.posix_spawn{.interpreted-text role="func"} now acceptsNonefor the env argument, which makes the newly spawned process use the current process environment. (Contributed by Jakub Kulik in113119{.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 in113117{.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 in88569{.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 in44626{.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 in82367{.interpreted-text role="gh"}.)
pathlib
- Add
~pathlib.UnsupportedOperation{.interpreted-text role="exc"}, which is raised instead ofNotImplementedError{.interpreted-text role="exc"} when a path operation isn't supported. (Contributed by Barney Gale in89812{.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 in107465{.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 in73435{.interpreted-text role="gh"}.) - Add the
.PurePath.parser{.interpreted-text role="attr"} class attribute to store the implementation ofos.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 in77609{.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 in70303{.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 in105793{.interpreted-text role="gh"} and Kamil Turek in107962{.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 in118579{.interpreted-text role="gh"}.)sys.path[0]is no longer replaced by the directory of the script being debugged whensys.flags.safe_path{.interpreted-text role="attr"} is set. (Contributed by Tian Gao and Christian Walther in111762{.interpreted-text role="gh"}.)zipapp{.interpreted-text role="mod"} is now supported as a debugging target. (Contributed by Tian Gao in118501{.interpreted-text role="gh"}.)- Add ability to move between chained exceptions during post-mortem debugging in
~pdb.pm{.interpreted-text role="func"} using the newexceptions [exc_number] <exceptions>{.interpreted-text role="pdbcmd"} command for Pdb. (Contributed by Matthias Bussonnier in106676{.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 in104750{.interpreted-text role="gh"}.)
random
- Add a
command-line interface <random-cli>{.interpreted-text role="ref"}. (Contributed by Hugo van Kemenade in118131{.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 in62308{.interpreted-text role="gh"})
site
.pth{.interpreted-text role="file"} files are now decoded using UTF-8 first, and then with thelocale encoding{.interpreted-text role="term"} if UTF-8 decoding fails. (Contributed by Inada Naoki in117802{.interpreted-text role="gh"}.)
sqlite3
- A
ResourceWarning{.interpreted-text role="exc"} is now emitted if a~sqlite3.Connection{.interpreted-text role="class"} object is notclosed <sqlite3.Connection.close>{.interpreted-text role="meth"} explicitly. (Contributed by Erlend E. Aasland in105539{.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 in91602{.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 in115863{.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 in115863{.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 toFalseif you need to forcesubprocess{.interpreted-text role="mod"} to never use~os.posix_spawn{.interpreted-text role="func"}. Please report your reason and platform details in theissue 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 in113117{.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 in78573{.interpreted-text role="gh"}.)
tempfile
- On Windows, the default mode
0o700used bytempfile.mkdtemp{.interpreted-text role="func"} now limits access to the new directory due to changes toos.mkdir{.interpreted-text role="func"}. This is a mitigation for2024-4030{.interpreted-text role="cve"}. (Contributed by Steve Dower in118486{.interpreted-text role="gh"}.)
time
- On Windows,
~time.monotonic{.interpreted-text role="func"} now uses theQueryPerformanceCounter()clock for a resolution of 1 microsecond, instead of theGetTickCount64()clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in88494{.interpreted-text role="gh"}.) - On Windows,
~time.time{.interpreted-text role="func"} now uses theGetSystemTimePreciseAsFileTime()clock for a resolution of 1 microsecond, instead of theGetSystemTimeAsFileTime()clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in63207{.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 in72684{.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 examplew.wm_attributes('alpha')and allows specifying attributes and values to set as keyword arguments, for examplew.wm_attributes(alpha=0.5). (Contributed by Serhiy Storchaka in43457{.interpreted-text role="gh"}.) !wm_attributes{.interpreted-text role="meth"} can now return attributes as adict{.interpreted-text role="class"}, by using the new optional keyword-only parameter return_python_dict. (Contributed by Serhiy Storchaka in43457{.interpreted-text role="gh"}.)!Text.count{.interpreted-text role="meth"} can now return a simpleint{.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 orNone. (Contributed by Serhiy Storchaka in97928{.interpreted-text role="gh"}.)- Support the "vsapi" element type in the
~tkinter.ttk.Style.element_create{.interpreted-text role="meth"} method oftkinter.ttk.Style{.interpreted-text role="class"}. (Contributed by Serhiy Storchaka in68166{.interpreted-text role="gh"}.) - Add the
!after_info{.interpreted-text role="meth"} method for Tkinter widgets. (Contributed by Cheryl Sabella in77020{.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 in118225{.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 in118225{.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 in118271{.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 (defaultTrue) to indicate whetherexc_typeshould be saved. (Contributed by Irit Katriel in112332{.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 aBaseExceptionGroup{.interpreted-text role="exc"} instance. (Contributed by Irit Katriel in105292{.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 in108191{.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 thetyping{.interpreted-text role="mod"} module. (Contributed by Jelle Zijlstra in116126{.interpreted-text role="gh"}.) - Add
~typing.get_protocol_members{.interpreted-text role="func"} to return the set of members defining atyping.Protocol{.interpreted-text role="class"}. (Contributed by Jelle Zijlstra in104873{.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 in104873{.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 in89547{.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 in108125{.interpreted-text role="gh"}.)
warnings
702{.interpreted-text role="pep"}: The newwarnings.deprecated{.interpreted-text role="func"} decorator provides a way to communicate deprecations to astatic type checker{.interpreted-text role="term"} and to warn on usage of deprecated classes and functions. ADeprecationWarning{.interpreted-text role="exc"} may also be emitted when a decorated function or class is used at runtime. (Contributed by Jelle Zijlstra in104003{.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 in69893{.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 onre{.interpreted-text role="mod"} andcontextlib{.interpreted-text role="mod"}. Other modules to enjoy import-time speedups includeemail.utils{.interpreted-text role="mod"},enum{.interpreted-text role="mod"},functools{.interpreted-text role="mod"},importlib.metadata{.interpreted-text role="mod"}, andthreading{.interpreted-text role="mod"}. (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas, and others in109653{.interpreted-text role="gh"}.) textwrap.indent{.interpreted-text role="func"} is now around 30% faster than before for large input. (Contributed by Inada Naoki in107369{.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 isTrue(the default) on many modern platforms. This should provide a notable performance increase when launching processes on FreeBSD and Solaris. See thesubprocess <whatsnew313-subprocess>{.interpreted-text role="ref"} section above for details. (Contributed by Jakub Kulik in113117{.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 ofaifclibrary from PyPI.
!audioop{.interpreted-text role="mod"}audioop-lts{.interpreted-text role="pypi"}: Useaudioop-ltslibrary from PyPI.
!chunk{.interpreted-text role="mod"}standard-chunk{.interpreted-text role="pypi"}: Use the redistribution ofchunklibrary from PyPI.
!cgi{.interpreted-text role="mod"} and!cgitb{.interpreted-text role="mod"}!cgi.FieldStorage{.interpreted-text role="class"} can typically be replaced withurllib.parse.parse_qsl{.interpreted-text role="func"} forGETandHEADrequests, and theemail.message{.interpreted-text role="mod"} module or themultipart{.interpreted-text role="pypi"} library forPOSTandPUTrequests.!cgi.parse{.interpreted-text role="func"} can be replaced by callingurllib.parse.parse_qs{.interpreted-text role="func"} directly on the desired query string, unless the input ismultipart/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 theemail{.interpreted-text role="mod"} package, which implements the same MIME RFCs. For example, withemail.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 theemail{.interpreted-text role="mod"} package, which implements the same MIME RFCs, or with themultipart{.interpreted-text role="pypi"} library. For example, theemail.message.EmailMessage{.interpreted-text role="class"} andemail.message.Message{.interpreted-text role="class"} classes.standard-cgi{.interpreted-text role="pypi"}: andstandard-cgitb{.interpreted-text role="pypi"}: Use the redistribution ofcgiandcgitblibrary from PyPI.
!crypt{.interpreted-text role="mod"} and the private!_crypt{.interpreted-text role="mod"} extension. Thehashlib{.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 thecrypt_r(3){.interpreted-text role="manpage"} library call and associated functionality.standard-crypt{.interpreted-text role="pypi"} anddeprecated-crypt-alternative{.interpreted-text role="pypi"}: Use the redistribution ofcryptand reimplementation of_cryptlibraries from PyPI.
!imghdr{.interpreted-text role="mod"}: Thefiletype{.interpreted-text role="pypi"},puremagic{.interpreted-text role="pypi"}, orpython-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 ofimghdrlibrary from PyPI.
!mailcap{.interpreted-text role="mod"}: Use themimetypes{.interpreted-text role="mod"} module instead.standard-mailcap{.interpreted-text role="pypi"}: Use the redistribution ofmailcaplibrary from PyPI.
!msilib{.interpreted-text role="mod"}!nis{.interpreted-text role="mod"}!nntplib{.interpreted-text role="mod"}: Use thepynntp{.interpreted-text role="pypi"} library from PyPI instead.standard-nntplib{.interpreted-text role="pypi"}: Use the redistribution ofnntpliblibrary from PyPI.
!ossaudiodev{.interpreted-text role="mod"}: For audio playback, use thepygame{.interpreted-text role="pypi"} library from PyPI instead.!pipes{.interpreted-text role="mod"}: Use thesubprocess{.interpreted-text role="mod"} module instead. Useshlex.quote{.interpreted-text role="func"} to replace the undocumentedpipes.quotefunction.standard-pipes{.interpreted-text role="pypi"}: Use the redistribution ofpipeslibrary from PyPI.
!sndhdr{.interpreted-text role="mod"}: Thefiletype{.interpreted-text role="pypi"},puremagic{.interpreted-text role="pypi"}, orpython-magic{.interpreted-text role="pypi"} libraries should be used as replacements.standard-sndhdr{.interpreted-text role="pypi"}: Use the redistribution ofsndhdrlibrary from PyPI.
!spwd{.interpreted-text role="mod"}: Use thepython-pam{.interpreted-text role="pypi"} library from PyPI instead.!sunau{.interpreted-text role="mod"}standard-sunau{.interpreted-text role="pypi"}: Use the redistribution ofsunaulibrary from PyPI.
!telnetlib{.interpreted-text role="mod"}, Use thetelnetlib3{.interpreted-text role="pypi"} orExscript{.interpreted-text role="pypi"} libraries from PyPI instead.standard-telnetlib{.interpreted-text role="pypi"}: Use the redistribution oftelnetliblibrary from PyPI.
!uu{.interpreted-text role="mod"}: Use thebase64{.interpreted-text role="mod"} module instead, as a modern alternative.standard-uu{.interpreted-text role="pypi"}: Use the redistribution ofuulibrary from PyPI.
!xdrlib{.interpreted-text role="mod"}standard-xdrlib{.interpreted-text role="pypi"}: Use the redistribution ofxdrliblibrary 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 in104780{.interpreted-text role="gh"}.)
builtins
- Remove support for chained
classmethod{.interpreted-text role="class"} descriptors (introduced in63272{.interpreted-text role="gh"}). These can no longer be used to wrap other descriptors, such asproperty{.interpreted-text role="class"}. The core design of this feature was flawed and led to several problems. To "pass-through" aclassmethod{.interpreted-text role="class"}, consider using the!__wrapped__{.interpreted-text role="attr"} attribute that was added in Python 3.10. (Contributed by Raymond Hettinger in89519{.interpreted-text role="gh"}.) - Raise a
RuntimeError{.interpreted-text role="exc"} when callingframe.clear{.interpreted-text role="meth"} on a suspended frame (as has always been the case for an executing frame). (Contributed by Irit Katriel in79932{.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 in104886{.interpreted-text role="gh"}.)
importlib.metadata
- Remove deprecated subscript (
~object.__getitem__{.interpreted-text role="meth"}) access forEntryPoint <entry-points>{.interpreted-text role="ref"} objects. (Contributed by Jason R. Coombs in113175{.interpreted-text role="gh"}.)
locale
- Remove the
!locale.resetlocale{.interpreted-text role="func"} function, deprecated in Python 3.11. Uselocale.setlocale(locale.LC_ALL, "")instead. (Contributed by Victor Stinner in104783{.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 in105481{.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 throughdis{.interpreted-text role="mod"}, and were not intended to be used externally. (Contributed by Irit Katriel in105481{.interpreted-text role="gh"}.)
optparse
- This module is no longer considered
soft deprecated{.interpreted-text role="term"}. Whileargparse{.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 wayargparseworks that mean the lower leveloptparsemodule may provide a better foundation for writing argument processing libraries, and for implementing command line applications which adhere more strictly thanargparsedoes 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 in126180{.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 in83863{.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 in105687{.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 in75552{.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 in104876{.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 thetyping{.interpreted-text role="mod"} module. (Contributed by Sebastian Rittau in92871{.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 in104786{.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 in104992{.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. Thessl.SSLContext.load_cert_chain{.interpreted-text role="meth"} function can be used to load specific certificates, or letssl.create_default_context{.interpreted-text role="func"} select the operating system's trusted certificate authority (CA) certificates. (Contributed by Victor Stinner in105382{.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 in104804{.interpreted-text role="gh"}.) - Remove the deprecated
!MacOSXOSAScript._name{.interpreted-text role="attr"} attribute. Use theMacOSXOSAScript.name <webbrowser.controller.name>{.interpreted-text role="attr"} attribute instead. (Contributed by Nikita Sobolev in105546{.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 in81137{.interpreted-text role="gh"}.)
- Deprecate assignment to a function's
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 in80480{.interpreted-text role="gh"}.)
- Deprecate the
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 in105733{.interpreted-text role="gh"}.) Soft-deprecate <soft deprecated>{.interpreted-text role="term"} the~ctypes.ARRAY{.interpreted-text role="func"} function in favour oftype * lengthmultiplication. (Contributed by Victor Stinner in105733{.interpreted-text role="gh"}.)
- Deprecate the undocumented
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 in89902{.interpreted-text role="gh"}.)
- Deprecate the non-standard and undocumented
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 in109319{.interpreted-text role="gh"}.)
- Deprecate the
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 in88434{.interpreted-text role="gh"}.)
- Deprecate non-integer numbers as arguments to functions and methods that consider plural forms in the
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 apath-like object{.interpreted-text role="term"} specifying the root directory to the root_dir parameter instead. (Contributed by Barney Gale in117337{.interpreted-text role="gh"}.)
- Deprecate the undocumented
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 in109096{.interpreted-text role="gh"}.) - Deprecate the
!--cgi{.interpreted-text role="option"} flag to thepython -m http.server{.interpreted-text role="program"} command-line interface, to be removed in Python 3.15. (Contributed by Gregory P. Smith in109096{.interpreted-text role="gh"}.)
- Deprecate
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 in66543{.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 becomekeyword-only <keyword-only_parameter>{.interpreted-text role="ref"} in a future version of Python. (Contributed by Serhiy Storchaka in56166{.interpreted-text role="gh"}.)
- Deprecate passing the optional maxsplit, count, or flags arguments as positional arguments to the module-level
pathlib{.interpreted-text role="mod"}:- Deprecate
!.PurePath.is_reserved{.interpreted-text role="meth"}, to be removed in Python 3.15. Useos.path.isreserved{.interpreted-text role="func"} to detect reserved paths on Windows. (Contributed by Barney Gale in88569{.interpreted-text role="gh"}.)
- Deprecate
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 in116349{.interpreted-text role="gh"}.)
- Deprecate
pydoc{.interpreted-text role="mod"}:- Deprecate the undocumented
!ispackage{.interpreted-text role="func"} function. (Contributed by Zackery Spytz in64020{.interpreted-text role="gh"}.)
- Deprecate the undocumented
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 in107948{.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 in108278{.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 in108278{.interpreted-text role="gh"}.)
- Deprecate passing more than one positional argument to the
sys{.interpreted-text role="mod"}:- Deprecate the
~sys._enablelegacywindowsfsencoding{.interpreted-text role="func"} function, to be removed in Python 3.16. Use thePYTHONLEGACYWINDOWSFSENCODING{.interpreted-text role="envvar"} environment variable instead. (Contributed by Inada Naoki in73427{.interpreted-text role="gh"}.)
- Deprecate the
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 in115256{.interpreted-text role="gh"}.)
- Deprecate the undocumented and unused
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 in112332{.interpreted-text role="gh"}.)
- Deprecate the
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 in105566{.interpreted-text role="gh"}.) - Deprecate omitting the fields parameter when creating a
~typing.NamedTuple{.interpreted-text role="class"} ortyping.TypedDict{.interpreted-text role="class"} class, and deprecate passingNoneto 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, useclass NT(NamedTuple): passorNT = NamedTuple("NT", ()). To create a TypedDict class with zero fields, useclass TD(TypedDict): passorTD = TypedDict("TD", {}). (Contributed by Alex Waygood in105566{.interpreted-text role="gh"} and105570{.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 thetyping{.interpreted-text role="mod"} module, it has yet to be supported by any major type checker. (Contributed by Alex Waygood in106309{.interpreted-text role="gh"}.) - Deprecate
typing.AnyStr{.interpreted-text role="data"}. In Python 3.16, it will be removed fromtyping.__all__, and aDeprecationWarning{.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 newtype parameter syntax <type-params>{.interpreted-text role="ref"} instead. (Contributed by Michael The in107116{.interpreted-text role="gh"}.)
- Deprecate the undocumented keyword argument syntax for creating
wave{.interpreted-text role="mod"}:- Deprecate the
getmark(),setmark()andgetmarkers()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 in105096{.interpreted-text role="gh"}.)
- Deprecate the
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 in92248{.interpreted-text role="gh"}.)ast{.interpreted-text role="mod"}: The following features have been deprecated in documentation since Python 3.8, now cause aDeprecationWarning{.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 in90953{.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 in94597{.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 in94597{.interpreted-text role="gh"}.)- The
~asyncio.get_event_loop{.interpreted-text role="meth"} method of the default event loop policy now emits aDeprecationWarning{.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 in100160{.interpreted-text role="gh"}.)
- The child watcher classes
email{.interpreted-text role="mod"}: Deprecated the isdst parameter inemail.utils.localtime{.interpreted-text role="func"}. (Contributed by Alan Williams in72346{.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 in101588{.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'. Seemultiprocessing-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 raiseDeprecationWarning{.interpreted-text role="exc"}; useimportlib.util.find_spec{.interpreted-text role="func"} instead. (Contributed by Nikita Sobolev in97850{.interpreted-text role="gh"}.)pty{.interpreted-text role="mod"}:master_open(): usepty.openpty{.interpreted-text role="func"}.slave_open(): usepty.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"} ifnamed placeholders <sqlite3-placeholders>{.interpreted-text role="ref"} are used and parameters is a sequence instead of adict{.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 in88168{.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"})
- Setting
ctypes{.interpreted-text role="mod"}:- The undocumented
!ctypes.SetPointerType{.interpreted-text role="func"} function has been deprecated since Python 3.13.
- The undocumented
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 thepython -m http.server{.interpreted-text role="program"} command-line interface has been deprecated since Python 3.13.
- The obsolete and rarely used
importlib{.interpreted-text role="mod"}:load_module()method: useexec_module()instead.
pathlib{.interpreted-text role="mod"}:!.PurePath.is_reserved{.interpreted-text role="meth"} has been deprecated since Python 3.13. Useos.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.
- The check_home argument of
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 in626{.interpreted-text role="pep"} since 3.10 and was planned to be removed in 3.12, but it only got a properDeprecationWarning{.interpreted-text role="exc"} in 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in101866{.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 passingNone(TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Useclass TD(TypedDict): passorTD = 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 thetyping{.interpreted-text role="mod"} module, it has yet to be supported by any major type checker.
- The undocumented keyword argument syntax for creating
!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()andgetmarkers()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.
- The
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.
- Setting
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.
- The
asyncio{.interpreted-text role="mod"}:!asyncio.iscoroutinefunction{.interpreted-text role="func"} is deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunction{.interpreted-text role="func"} instead. (Contributed by Jiahao Li and Kumar Aditya in122875{.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"} orasyncio.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,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
- Bitwise inversion on boolean types,
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.
- Calling the Python implementation of
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"}.)
- 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
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 aValueError{.interpreted-text role="exc"} in Python 3.16. (Contributed by Hugo van Kemenade in75223{.interpreted-text role="gh"}.)
- Valid extensions start with a '.' or are empty for
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 ofRuntimeError{.interpreted-text role="exc"}.
- The
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.
- The
sys{.interpreted-text role="mod"}:- The
~sys._enablelegacywindowsfsencoding{.interpreted-text role="func"} function has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODING{.interpreted-text role="envvar"} environment variable instead.
- The
sysconfig{.interpreted-text role="mod"}:- The
!sysconfig.expand_makefile_vars{.interpreted-text role="func"} function has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_paths{.interpreted-text role="func"} instead.
- The
tarfile{.interpreted-text role="mod"}:- The undocumented and unused
!TarFile.tarfile{.interpreted-text role="attr"} attribute has been deprecated since Python 3.13.
- The undocumented and unused
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 ifobjimplements thebuffer 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 bothbytes{.interpreted-text role="class"} andbytearray{.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 asmemoryview{.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 in91896{.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 in136702{.interpreted-text role="gh"})
- Passing non-ascii encoding names to
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 liketyping.get_origin{.interpreted-text role="func"} andtyping.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 ifobjimplements thebuffer 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 bothbytes{.interpreted-text role="class"} andbytearray{.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 asmemoryview{.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 in91896{.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 in89902{.interpreted-text role="gh"}.)
- The non-standard and undocumented
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.
- Implicitly switching to the MSVC-compatible struct layout by setting
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 nameddata=orstring=in various!hashlib{.interpreted-text role="mod"} implementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword 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__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.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"} (usedecimal.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)andathrow(type, exc, tb)signature is deprecated: usethrow(exc)andathrow(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 keywordsand{.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"} andor{.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 ofint{.interpreted-text role="class"}. - Support for
__float__()method returning a strict subclass offloat{.interpreted-text role="class"}: these methods will be required to return an instance offloat{.interpreted-text role="class"}. - Support for
__complex__()method returning a strict subclass ofcomplex{.interpreted-text role="class"}: these methods will be required to return an instance ofcomplex{.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 in109218{.interpreted-text role="gh"}.)
- Generators:
calendar{.interpreted-text role="mod"}:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARY{.interpreted-text role="data"} andcalendar.FEBRUARY{.interpreted-text role="data"}. (Contributed by Prince Roshan in103636{.interpreted-text role="gh"}.)codecs{.interpreted-text role="mod"}: useopen{.interpreted-text role="func"} instead ofcodecs.open{.interpreted-text role="func"}. (133038{.interpreted-text role="gh"})codeobject.co_lnotab{.interpreted-text role="attr"}: use thecodeobject.co_lines{.interpreted-text role="meth"} method instead.datetime{.interpreted-text role="mod"}:~datetime.datetime.utcnow{.interpreted-text role="meth"}: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp{.interpreted-text role="meth"}: usedatetime.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"}:EntryPointstuple interface.- Implicit
Noneon return values.
logging{.interpreted-text role="mod"}: thewarn()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"}: Callingos.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, useos.path.commonpath{.interpreted-text role="func"} for path prefixes. Theos.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 in91760{.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*optionsssl.OP_NO_TLS*optionsssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.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"}: usethreading.Thread.daemon{.interpreted-text role="attr"} attribute.!threading.Thread.getName{.interpreted-text role="meth"},threading.Thread.setName{.interpreted-text role="meth"}: usethreading.Thread.name{.interpreted-text role="attr"} attribute.!threading.currentThread{.interpreted-text role="meth"}: usethreading.current_thread{.interpreted-text role="meth"}.!threading.activeCount{.interpreted-text role="meth"}: usethreading.active_count{.interpreted-text role="meth"}.
typing.Text{.interpreted-text role="class"} (92332{.interpreted-text role="gh"}).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.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 in105499{.interpreted-text role="gh"}.) unittest.IsolatedAsyncioTestCase{.interpreted-text role="class"}: it is deprecated to return a value that is notNonefrom a test case.urllib.parse{.interpreted-text role="mod"} deprecated functions:~urllib.parse.urlparse{.interpreted-text role="func"} insteadsplitattr()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 returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cache{.interpreted-text role="func"} is deprecated: usesys._clear_internal_caches{.interpreted-text role="func"} instead.
CPython Bytecode Changes
- The oparg of
YIELD_VALUE{.interpreted-text role="opcode"} is now1if the yield is part of a yield-from or await, and0otherwise. The oparg ofRESUME{.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 in111354{.interpreted-text role="gh"}.)
C API Changes
New Features
Add the
PyMonitoring C API <c-api-monitoring>{.interpreted-text role="ref"} for generating669{.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_FireBranchEventPyMonitoring_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 newPyMutex_Lock{.interpreted-text role="c:func"} andPyMutex_Unlock{.interpreted-text role="c:func"} functions.!PyMutex_Lock{.interpreted-text role="c:func"} will release theGIL{.interpreted-text role="term"} (if currently held) if the operation needs to block. (Contributed by Sam Gross in108724{.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"} andPyTime_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 asPyDict_Contains{.interpreted-text role="c:func"}, but key is specified as aconst char*{.interpreted-text role="c:expr"} UTF-8 encoded bytes string, rather than aPyObject*{.interpreted-text role="c:expr"}. (Contributed by Victor Stinner in108314{.interpreted-text role="gh"}.)Add the
PyDict_GetItemRef{.interpreted-text role="c:func"} andPyDict_GetItemStringRef{.interpreted-text role="c:func"} functions, which behave similarly toPyDict_GetItemWithError{.interpreted-text role="c:func"}, but return astrong reference{.interpreted-text role="term"} instead of aborrowed reference{.interpreted-text role="term"}. Moreover, these functions return-1on error, removing the need to check!PyErr_Occurred{.interpreted-text role="c:func"}. (Contributed by Victor Stinner in106004{.interpreted-text role="gh"}.)Add the
PyDict_SetDefaultRef{.interpreted-text role="c:func"} function, which behaves similarly toPyDict_SetDefault{.interpreted-text role="c:func"}, but returns astrong reference{.interpreted-text role="term"} instead of aborrowed reference{.interpreted-text role="term"}. This function returns-1on error,0on insertion, and1if the key was already present in the dictionary. (Contributed by Sam Gross in112066{.interpreted-text role="gh"}.)Add the
PyDict_Pop{.interpreted-text role="c:func"} andPyDict_PopString{.interpreted-text role="c:func"} functions to remove a key from a dictionary and optionally return the removed value. This is similar todict.pop{.interpreted-text role="meth"}, though there is no default value, andKeyError{.interpreted-text role="exc"} is not raised for missing keys. (Contributed by Stefan Behnel and Victor Stinner in111262{.interpreted-text role="gh"}.)Add the
PyMapping_GetOptionalItem{.interpreted-text role="c:func"} andPyMapping_GetOptionalItemString{.interpreted-text role="c:func"} functions as alternatives toPyObject_GetItem{.interpreted-text role="c:func"} andPyMapping_GetItemString{.interpreted-text role="c:func"} respectively. The new functions do not raiseKeyError{.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 in106307{.interpreted-text role="gh"}.)Add the
PyObject_GetOptionalAttr{.interpreted-text role="c:func"} andPyObject_GetOptionalAttrString{.interpreted-text role="c:func"} functions as alternatives toPyObject_GetAttr{.interpreted-text role="c:func"} andPyObject_GetAttrString{.interpreted-text role="c:func"} respectively. The new functions do not raiseAttributeError{.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 in106521{.interpreted-text role="gh"}.)Add the
PyErr_FormatUnraisable{.interpreted-text role="c:func"} function as an extension toPyErr_WriteUnraisable{.interpreted-text role="c:func"} that allows customizing the warning message. (Contributed by Serhiy Storchaka in108082{.interpreted-text role="gh"}.)Add new functions that return a
strong reference{.interpreted-text role="term"} instead of aborrowed reference{.interpreted-text role="term"} for frame locals, globals, and builtins, as part ofPEP 667 <whatsnew313-locals-semantics>{.interpreted-text role="ref"}:PyEval_GetFrameBuiltins{.interpreted-text role="c:func"} replacesPyEval_GetBuiltins{.interpreted-text role="c:func"}PyEval_GetFrameGlobals{.interpreted-text role="c:func"} replacesPyEval_GetGlobals{.interpreted-text role="c:func"}PyEval_GetFrameLocals{.interpreted-text role="c:func"} replacesPyEval_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"} andPy_GetConstantBorrowed{.interpreted-text role="c:func"} functions to getstrong <strong reference>{.interpreted-text role="term"} orborrowed <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 in115754{.interpreted-text role="gh"}.)Add the
PyImport_AddModuleRef{.interpreted-text role="c:func"} function as a replacement forPyImport_AddModule{.interpreted-text role="c:func"} that returns astrong reference{.interpreted-text role="term"} instead of aborrowed reference{.interpreted-text role="term"}. (Contributed by Victor Stinner in105922{.interpreted-text role="gh"}.)Add the
Py_IsFinalizing{.interpreted-text role="c:func"} function to check whether the main Python interpreter isshutting down <interpreter shutdown>{.interpreted-text role="term"}. (Contributed by Victor Stinner in108014{.interpreted-text role="gh"}.)Add the
PyList_GetItemRef{.interpreted-text role="c:func"} function as a replacement forPyList_GetItem{.interpreted-text role="c:func"} that returns astrong reference{.interpreted-text role="term"} instead of aborrowed reference{.interpreted-text role="term"}. (Contributed by Sam Gross in114329{.interpreted-text role="gh"}.)Add the
PyList_Extend{.interpreted-text role="c:func"} andPyList_Clear{.interpreted-text role="c:func"} functions, mirroring the Pythonlist.extend{.interpreted-text role="meth"} andlist.clear{.interpreted-text role="meth"} methods. (Contributed by Victor Stinner in111138{.interpreted-text role="gh"}.)Add the
PyLong_AsInt{.interpreted-text role="c:func"} function. It behaves similarly toPyLong_AsLong{.interpreted-text role="c:func"}, but stores the result in a Cint{.interpreted-text role="c:expr"} instead of a Clong{.interpreted-text role="c:expr"}. (Contributed by Victor Stinner in108014{.interpreted-text role="gh"}.)Add the
PyLong_AsNativeBytes{.interpreted-text role="c:func"},PyLong_FromNativeBytes{.interpreted-text role="c:func"}, andPyLong_FromUnsignedNativeBytes{.interpreted-text role="c:func"} functions to simplify converting between native integer types and Pythonint{.interpreted-text role="class"} objects. (Contributed by Steve Dower in111140{.interpreted-text role="gh"}.)Add
PyModule_Add{.interpreted-text role="c:func"} function, which is similar toPyModule_AddObjectRef{.interpreted-text role="c:func"} andPyModule_AddObject{.interpreted-text role="c:func"}, but always steals a reference to the value. (Contributed by Serhiy Storchaka in86493{.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 in113024{.interpreted-text role="gh"}.)Add the
Py_HashPointer{.interpreted-text role="c:func"} function to hash a raw pointer. (Contributed by Victor Stinner in111545{.interpreted-text role="gh"}.)Add the
PyObject_VisitManagedDict{.interpreted-text role="c:func"} andPyObject_ClearManagedDict{.interpreted-text role="c:func"} functions. which must be called by the traverse and clear functions of a type using thePy_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 in107073{.interpreted-text role="gh"}.)Add the
PyRefTracer_SetTracer{.interpreted-text role="c:func"} andPyRefTracer_GetTracer{.interpreted-text role="c:func"} functions, which enable tracking object creation and destruction in the same way that thetracemalloc{.interpreted-text role="mod"} module does. (Contributed by Pablo Galindo in93502{.interpreted-text role="gh"}.)Add the
PySys_AuditTuple{.interpreted-text role="c:func"} function as an alternative toPySys_Audit{.interpreted-text role="c:func"} that takes event arguments as a Pythontuple{.interpreted-text role="class"} object. (Contributed by Victor Stinner in85283{.interpreted-text role="gh"}.)Add the
PyThreadState_GetUnchecked(){.interpreted-text role="c:func"} function as an alternative toPyThreadState_Get(){.interpreted-text role="c:func"} that doesn't kill the process with a fatal error if it isNULL. The caller is responsible for checking if the result isNULL. (Contributed by Victor Stinner in108867{.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 iftype.__module__{.interpreted-text role="attr"} is a string and is not equal to either'builtins'or'__main__'. (Contributed by Victor Stinner in111696{.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 thetype.__module__{.interpreted-text role="attr"} attribute. (Contributed by Eric Snow and Victor Stinner in111696{.interpreted-text role="gh"}.)Add the
PyUnicode_EqualToUTF8AndSize{.interpreted-text role="c:func"} andPyUnicode_EqualToUTF8{.interpreted-text role="c:func"} functions to compare a Unicode object with aconst char*{.interpreted-text role="c:expr"} UTF-8 encoded string and1if they are equal or0otherwise. These functions do not raise exceptions. (Contributed by Serhiy Storchaka in110289{.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 astrong reference{.interpreted-text role="term"} orNULLif the referent is no longer live. (Contributed by Victor Stinner in105927{.interpreted-text role="gh"}.)Add fixed variants of functions which silently ignore errors:
PyObject_HasAttrWithError{.interpreted-text role="c:func"} replacesPyObject_HasAttr{.interpreted-text role="c:func"}.PyObject_HasAttrStringWithError{.interpreted-text role="c:func"} replacesPyObject_HasAttrString{.interpreted-text role="c:func"}.PyMapping_HasKeyWithError{.interpreted-text role="c:func"} replacesPyMapping_HasKey{.interpreted-text role="c:func"}.PyMapping_HasKeyStringWithError{.interpreted-text role="c:func"} replacesPyMapping_HasKeyString{.interpreted-text role="c:func"}.
The new functions return
-1for errors and the standard1for true and0for 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"} andPyArg_VaParseTupleAndKeywords{.interpreted-text role="c:func"} now has typechar * const *{.interpreted-text role="c:expr"} in C andconst char * const *{.interpreted-text role="c:expr"} in C++, instead ofchar **{.interpreted-text role="c:expr"}. In C++, this makes these functions compatible with arguments of typeconst char * const *{.interpreted-text role="c:expr"},const char **{.interpreted-text role="c:expr"}, orchar * const *{.interpreted-text role="c:expr"} without an explicit type cast. In C, the functions only support arguments of typechar * const *{.interpreted-text role="c:expr"}. This can be overridden with thePY_CXX_CONST{.interpreted-text role="c:macro"} macro. (Contributed by Serhiy Storchaka in65210{.interpreted-text role="gh"}.)PyArg_ParseTupleAndKeywords{.interpreted-text role="c:func"} now supports non-ASCII keyword parameter names. (Contributed by Serhiy Storchaka in110815{.interpreted-text role="gh"}.)The
!PyCode_GetFirstFree{.interpreted-text role="c:func"} function is now unstable API and is now namedPyUnstable_Code_GetFirstFree{.interpreted-text role="c:func"}. (Contributed by Bogdan Romanyuk in115781{.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"}, andPySys_GetObject{.interpreted-text role="c:func"} functions, each of which clears all errors which occurred when calling them now reports these errors usingsys.unraisablehook{.interpreted-text role="func"}. You may replace them with other functions as recommended in the documentation. (Contributed by Serhiy Storchaka in106672{.interpreted-text role="gh"}.)Add support for the
%T,%#T,%Nand%#Nformats toPyUnicode_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 in111696{.interpreted-text role="gh"}.)You no longer have to define the
PY_SSIZE_T_CLEANmacro before includingPython.h{.interpreted-text role="file"} when using#formats informat codes <arg-parsing-string-and-buffers>{.interpreted-text role="ref"}. APIs accepting the format codes always usePy_ssize_tfor#formats. (Contributed by Inada Naoki in104922{.interpreted-text role="gh"}.)If Python is built in
debug mode <debug-build>{.interpreted-text role="ref"} orwith assertions <--with-assertions>{.interpreted-text role="option"},PyTuple_SET_ITEM{.interpreted-text role="c:func"} andPyList_SET_ITEM{.interpreted-text role="c:func"} now check the index argument with an assertion. (Contributed by Victor Stinner in106168{.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"} and116936{.interpreted-text role="gh"}.)Python built with
--with-trace-refs{.interpreted-text role="option"} (tracing references) now supports theLimited API <limited-c-api>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in108634{.interpreted-text role="gh"}.)
Removed C APIs
Remove several functions, macros, variables, etc with names prefixed by
_Pyor_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, pleaseopen a new issue <using-the-tracker>{.interpreted-text role="ref"} to request a public C API and addcc: @vstinnerto the issue to notify Victor Stinner. (Contributed by Victor Stinner in106320{.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"}: UsePyObject_CheckBuffer{.interpreted-text role="c:func"} to test whether the object supports the buffer protocol. Note thatPyObject_CheckBuffer{.interpreted-text role="c:func"} doesn't guarantee thatPyObject_GetBuffer{.interpreted-text role="c:func"} will succeed. To test if the object is actually readable, see the next example ofPyObject_GetBuffer{.interpreted-text role="c:func"}.!PyObject_AsCharBuffer{.interpreted-text role="c:func"},!PyObject_AsReadBuffer{.interpreted-text role="c:func"}: UsePyObject_GetBuffer{.interpreted-text role="c:func"} andPyBuffer_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"}: UsePyObject_GetBuffer{.interpreted-text role="c:func"} andPyBuffer_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"}: UsePyObject_CallNoArgs{.interpreted-text role="c:func"} orPyObject_Call{.interpreted-text role="c:func"} instead.:::: warning ::: title Warning :::
In
PyObject_Call{.interpreted-text role="c:func"}, positional arguments must be atuple{.interpreted-text role="class"} and must not beNULL, and keyword arguments must be adict{.interpreted-text role="class"} orNULL, whereas the removed functions checked argument types and acceptedNULLpositional and keyword arguments. To replacePyEval_CallObjectWithKeywords(func, NULL, kwargs)withPyObject_Call{.interpreted-text role="c:func"}, pass an empty tuple as positional arguments usingPyTuple_New(0) <PyTuple_New>{.interpreted-text role="c:func"}. ::::!PyEval_CallFunction{.interpreted-text role="c:func"}: UsePyObject_CallFunction{.interpreted-text role="c:func"} instead.!PyEval_CallMethod{.interpreted-text role="c:func"}: UsePyObject_CallMethod{.interpreted-text role="c:func"} instead.!PyCFunction_Call{.interpreted-text role="c:func"}: UsePyObject_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"}: UsePyConfig.warnoptions{.interpreted-text role="c:member"} instead.!PySys_AddWarnOption{.interpreted-text role="c:func"}: UsePyConfig.warnoptions{.interpreted-text role="c:member"} instead.!PySys_AddXOption{.interpreted-text role="c:func"}: UsePyConfig.xoptions{.interpreted-text role="c:member"} instead.!PySys_HasWarnOptions{.interpreted-text role="c:func"}: UsePyConfig.xoptions{.interpreted-text role="c:member"} instead.!PySys_SetPath{.interpreted-text role="c:func"}: SetPyConfig.module_search_paths{.interpreted-text role="c:member"} instead.!Py_SetPath{.interpreted-text role="c:func"}: SetPyConfig.module_search_paths{.interpreted-text role="c:member"} instead.!Py_SetStandardStreamEncoding{.interpreted-text role="c:func"}: SetPyConfig.stdio_encoding{.interpreted-text role="c:member"} instead, and set also maybePyConfig.legacy_windows_stdio{.interpreted-text role="c:member"} (on Windows).!_Py_SetProgramFullPath{.interpreted-text role="c:func"}: SetPyConfig.executable{.interpreted-text role="c:member"} instead.
Use the new
PyConfig{.interpreted-text role="c:type"} API of thePython Initialization Configuration <init-config>{.interpreted-text role="ref"} instead (587{.interpreted-text role="pep"}), added to Python 3.8. (Contributed by Victor Stinner in105145{.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"} andPyEval_RestoreThread{.interpreted-text role="c:func"};- low-level
PyEval_AcquireThread{.interpreted-text role="c:func"} andPyEval_RestoreThread{.interpreted-text role="c:func"}; - or
PyGILState_Ensure{.interpreted-text role="c:func"} andPyGILState_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 in105182{.interpreted-text role="gh"}.)Remove the
!_PyInterpreterState_Get{.interpreted-text role="c:func"} alias toPyInterpreterState_Get(){.interpreted-text role="c:func"} which was kept for backward compatibility with Python 3.8. The pythoncapi-compat project can be used to getPyInterpreterState_Get(){.interpreted-text role="c:func"} on Python 3.8 and older. (Contributed by Victor Stinner in106320{.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 in106023{.interpreted-text role="gh"}.)Remove the
cpython/pytime.hheader file, which only contained private functions. (Contributed by Victor Stinner in106316{.interpreted-text role="gh"}.)Remove the undocumented
PY_TIMEOUT_MAXconstant from the limited C API. (Contributed by Victor Stinner in110014{.interpreted-text role="gh"}.)Remove the old trashcan macros
Py_TRASHCAN_SAFE_BEGINandPy_TRASHCAN_SAFE_END. Replace both with the new macrosPy_TRASHCAN_BEGINandPy_TRASHCAN_END. (Contributed by Irit Katriel in105111{.interpreted-text role="gh"}.)
Deprecated C APIs
Deprecate old Python initialization functions:
!PySys_ResetWarnOptions{.interpreted-text role="c:func"}: Clearsys.warnoptions{.interpreted-text role="data"} and!warnings.filters{.interpreted-text role="data"} instead.!Py_GetExecPrefix{.interpreted-text role="c:func"}: Getsys.exec_prefix{.interpreted-text role="data"} instead.!Py_GetPath{.interpreted-text role="c:func"}: Getsys.path{.interpreted-text role="data"} instead.!Py_GetPrefix{.interpreted-text role="c:func"}: Getsys.prefix{.interpreted-text role="data"} instead.!Py_GetProgramFullPath{.interpreted-text role="c:func"}: Getsys.executable{.interpreted-text role="data"} instead.!Py_GetProgramName{.interpreted-text role="c:func"}: Getsys.executable{.interpreted-text role="data"} instead.!Py_GetPythonHome{.interpreted-text role="c:func"}: GetPyConfig.home{.interpreted-text role="c:member"} or thePYTHONHOME{.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"} thePyEval_GetBuiltins{.interpreted-text role="c:func"},PyEval_GetGlobals{.interpreted-text role="c:func"}, andPyEval_GetLocals{.interpreted-text role="c:func"} functions, which return aborrowed reference{.interpreted-text role="term"}. (Soft deprecated as part of667{.interpreted-text role="pep"}.)Deprecate the
!PyImport_ImportModuleNoBlock{.interpreted-text role="c:func"} function, which is just an alias toPyImport_ImportModule{.interpreted-text role="c:func"} since Python 3.3. (Contributed by Victor Stinner in105396{.interpreted-text role="gh"}.)Soft deprecate <soft deprecated>{.interpreted-text role="term"} thePyModule_AddObject{.interpreted-text role="c:func"} function. It should be replaced withPyModule_Add{.interpreted-text role="c:func"} orPyModule_AddObjectRef{.interpreted-text role="c:func"}. (Contributed by Serhiy Storchaka in86493{.interpreted-text role="gh"}.)Deprecate the old
Py_UNICODEandPY_UNICODE_TYPEtypes and the!Py_UNICODE_WIDE{.interpreted-text role="c:macro"} define. Use thewchar_t{.interpreted-text role="c:type"} type directly instead. Since Python 3.3,Py_UNICODEandPY_UNICODE_TYPEare just aliases to!wchar_t{.interpreted-text role="c:type"}. (Contributed by Victor Stinner in105156{.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 aborrowed reference{.interpreted-text role="term"}. Replace them with the newPyWeakref_GetRef{.interpreted-text role="c:func"} function, which returns astrong reference{.interpreted-text role="term"}. The pythoncapi-compat project can be used to getPyWeakref_GetRef{.interpreted-text role="c:func"} on Python 3.12 and older. (Contributed by Victor Stinner in105927{.interpreted-text role="gh"}.)
Pending removal in Python 3.14
- The
ma_version_tagfield inPyDictObject{.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"}: UsePyImport_ImportModule{.interpreted-text role="c:func"} instead.!PyWeakref_GetObject{.interpreted-text role="c:func"} and!PyWeakref_GET_OBJECT{.interpreted-text role="c:func"}: UsePyWeakref_GetRef{.interpreted-text role="c:func"} instead. The pythoncapi-compat project can be used to getPyWeakref_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: Usewchar_t{.interpreted-text role="c:type"} instead.!PyUnicode_AsDecodedObject{.interpreted-text role="c:func"}: UsePyCodec_Decode{.interpreted-text role="c:func"} instead.!PyUnicode_AsDecodedUnicode{.interpreted-text role="c:func"}: UsePyCodec_Decode{.interpreted-text role="c:func"} instead; Note that some codecs (for example, "base64") may return a type other thanstr{.interpreted-text role="class"}, such asbytes{.interpreted-text role="class"}.!PyUnicode_AsEncodedObject{.interpreted-text role="c:func"}: UsePyCodec_Encode{.interpreted-text role="c:func"} instead.!PyUnicode_AsEncodedUnicode{.interpreted-text role="c:func"}: UsePyCodec_Encode{.interpreted-text role="c:func"} instead; Note that some codecs (for example, "base64") may return a type other thanbytes{.interpreted-text role="class"}, such asstr{.interpreted-text role="class"}.Python initialization functions, deprecated in Python 3.13:
!Py_GetPath{.interpreted-text role="c:func"}: UsePyConfig_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"}: UsePyConfig_Get("base_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.base_prefix{.interpreted-text role="data"}) instead. UsePyConfig_Get("prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.prefix{.interpreted-text role="data"}) ifvirtual environments <venv-def>{.interpreted-text role="ref"} need to be handled.!Py_GetExecPrefix{.interpreted-text role="c:func"}: UsePyConfig_Get("base_exec_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.base_exec_prefix{.interpreted-text role="data"}) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.exec_prefix{.interpreted-text role="data"}) ifvirtual environments <venv-def>{.interpreted-text role="ref"} need to be handled.!Py_GetProgramFullPath{.interpreted-text role="c:func"}: UsePyConfig_Get("executable") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.executable{.interpreted-text role="data"}) instead.!Py_GetProgramName{.interpreted-text role="c:func"}: UsePyConfig_Get("executable") <PyConfig_Get>{.interpreted-text role="c:func"} (sys.executable{.interpreted-text role="data"}) instead.!Py_GetPythonHome{.interpreted-text role="c:func"}: UsePyConfig_Get("home") <PyConfig_Get>{.interpreted-text role="c:func"} or thePYTHONHOME{.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"}: SetPyConfig.argv{.interpreted-text role="c:member"} instead.!PySys_SetArgv(){.interpreted-text role="c:func"}: SetPyConfig.argv{.interpreted-text role="c:member"} instead.!Py_SetProgramName(){.interpreted-text role="c:func"}: SetPyConfig.program_name{.interpreted-text role="c:member"} instead.!Py_SetPythonHome(){.interpreted-text role="c:func"}: SetPyConfig.home{.interpreted-text role="c:member"} instead.!PySys_ResetWarnOptions{.interpreted-text role="c:func"}: Clearsys.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 withPyConfig{.interpreted-text role="c:type"} instead.Global configuration variables:
Py_DebugFlag{.interpreted-text role="c:var"}: UsePyConfig.parser_debug{.interpreted-text role="c:member"} orPyConfig_Get("parser_debug") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_VerboseFlag{.interpreted-text role="c:var"}: UsePyConfig.verbose{.interpreted-text role="c:member"} orPyConfig_Get("verbose") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_QuietFlag{.interpreted-text role="c:var"}: UsePyConfig.quiet{.interpreted-text role="c:member"} orPyConfig_Get("quiet") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_InteractiveFlag{.interpreted-text role="c:var"}: UsePyConfig.interactive{.interpreted-text role="c:member"} orPyConfig_Get("interactive") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_InspectFlag{.interpreted-text role="c:var"}: UsePyConfig.inspect{.interpreted-text role="c:member"} orPyConfig_Get("inspect") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_OptimizeFlag{.interpreted-text role="c:var"}: UsePyConfig.optimization_level{.interpreted-text role="c:member"} orPyConfig_Get("optimization_level") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_NoSiteFlag{.interpreted-text role="c:var"}: UsePyConfig.site_import{.interpreted-text role="c:member"} orPyConfig_Get("site_import") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_BytesWarningFlag{.interpreted-text role="c:var"}: UsePyConfig.bytes_warning{.interpreted-text role="c:member"} orPyConfig_Get("bytes_warning") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_FrozenFlag{.interpreted-text role="c:var"}: UsePyConfig.pathconfig_warnings{.interpreted-text role="c:member"} orPyConfig_Get("pathconfig_warnings") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_IgnoreEnvironmentFlag{.interpreted-text role="c:var"}: UsePyConfig.use_environment{.interpreted-text role="c:member"} orPyConfig_Get("use_environment") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_DontWriteBytecodeFlag{.interpreted-text role="c:var"}: UsePyConfig.write_bytecode{.interpreted-text role="c:member"} orPyConfig_Get("write_bytecode") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_NoUserSiteDirectory{.interpreted-text role="c:var"}: UsePyConfig.user_site_directory{.interpreted-text role="c:member"} orPyConfig_Get("user_site_directory") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_UnbufferedStdioFlag{.interpreted-text role="c:var"}: UsePyConfig.buffered_stdio{.interpreted-text role="c:member"} orPyConfig_Get("buffered_stdio") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_HashRandomizationFlag{.interpreted-text role="c:var"}: UsePyConfig.use_hash_seed{.interpreted-text role="c:member"} andPyConfig.hash_seed{.interpreted-text role="c:member"} orPyConfig_Get("hash_seed") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_IsolatedFlag{.interpreted-text role="c:var"}: UsePyConfig.isolated{.interpreted-text role="c:member"} orPyConfig_Get("isolated") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_LegacyWindowsFSEncodingFlag{.interpreted-text role="c:var"}: UsePyPreConfig.legacy_windows_fs_encoding{.interpreted-text role="c:member"} orPyConfig_Get("legacy_windows_fs_encoding") <PyConfig_Get>{.interpreted-text role="c:func"} instead.Py_LegacyWindowsStdioFlag{.interpreted-text role="c:var"}: UsePyConfig.legacy_windows_stdio{.interpreted-text role="c:member"} orPyConfig_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"}: UsePyConfig.filesystem_encoding{.interpreted-text role="c:member"} orPyConfig_Get("filesystem_encoding") <PyConfig_Get>{.interpreted-text role="c:func"} instead.!Py_FileSystemDefaultEncodeErrors{.interpreted-text role="c:var"}: UsePyConfig.filesystem_errors{.interpreted-text role="c:member"} orPyConfig_Get("filesystem_errors") <PyConfig_Get>{.interpreted-text role="c:func"} instead.!Py_UTF8Mode{.interpreted-text role="c:var"}: UsePyPreConfig.utf8_mode{.interpreted-text role="c:member"} orPyConfig_Get("utf8_mode") <PyConfig_Get>{.interpreted-text role="c:func"} instead. (seePy_PreInitialize{.interpreted-text role="c:func"})
The
Py_InitializeFromConfig{.interpreted-text role="c:func"} API should be used withPyConfig{.interpreted-text role="c:type"} to set these options. OrPyConfig_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"}: usePyBytes_Join{.interpreted-text role="c:func"}.!_PyDict_GetItemStringWithError{.interpreted-text role="c:func"}: usePyDict_GetItemStringRef{.interpreted-text role="c:func"}.!_PyDict_Pop(){.interpreted-text role="c:func"}: usePyDict_Pop{.interpreted-text role="c:func"}.!_PyLong_Sign(){.interpreted-text role="c:func"}: usePyLong_GetSign{.interpreted-text role="c:func"}.!_PyLong_FromDigits{.interpreted-text role="c:func"} and!_PyLong_New{.interpreted-text role="c:func"}: usePyLongWriter_Create{.interpreted-text role="c:func"}.!_PyThreadState_UncheckedGet{.interpreted-text role="c:func"}: usePyThreadState_GetUnchecked{.interpreted-text role="c:func"}.!_PyUnicode_AsString{.interpreted-text role="c:func"}: usePyUnicode_AsUTF8{.interpreted-text role="c:func"}.!_PyUnicodeWriter_Init{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_Init(&writer)withwriter = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_Finish{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_Finish(&writer)withPyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_Dealloc{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_Dealloc(&writer)withPyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_WriteChar{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_WriteChar(&writer, ch)withPyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_WriteStr{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_WriteStr(&writer, str)withPyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_WriteSubstring{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)withPyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_WriteASCIIString{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_WriteASCIIString(&writer, str)withPyUnicodeWriter_WriteASCII(writer, str) <PyUnicodeWriter_WriteASCII>{.interpreted-text role="c:func"}.!_PyUnicodeWriter_WriteLatin1String{.interpreted-text role="c:func"}: replace_PyUnicodeWriter_WriteLatin1String(&writer, str)withPyUnicodeWriter_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"}: usePy_HashPointer{.interpreted-text role="c:func"}.!_Py_fopen_obj{.interpreted-text role="c:func"}: usePy_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"}: UsePyErr_GetRaisedException{.interpreted-text role="c:func"} instead.PyErr_NormalizeException{.interpreted-text role="c:func"}: UsePyErr_GetRaisedException{.interpreted-text role="c:func"} instead.PyErr_Restore{.interpreted-text role="c:func"}: UsePyErr_SetRaisedException{.interpreted-text role="c:func"} instead.PyModule_GetFilename{.interpreted-text role="c:func"}: UsePyModule_GetFilenameObject{.interpreted-text role="c:func"} instead.PyOS_AfterFork{.interpreted-text role="c:func"}: UsePyOS_AfterFork_Child{.interpreted-text role="c:func"} instead.PySlice_GetIndicesEx{.interpreted-text role="c:func"}: UsePySlice_Unpack{.interpreted-text role="c:func"} andPySlice_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"}: UsePyErr_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: callPyObject_Hash{.interpreted-text role="c:func"} instead.- Thread Local Storage (TLS) API:
PyThread_create_key{.interpreted-text role="c:func"}: UsePyThread_tss_alloc{.interpreted-text role="c:func"} instead.PyThread_delete_key{.interpreted-text role="c:func"}: UsePyThread_tss_free{.interpreted-text role="c:func"} instead.PyThread_set_key_value{.interpreted-text role="c:func"}: UsePyThread_tss_set{.interpreted-text role="c:func"} instead.PyThread_get_key_value{.interpreted-text role="c:func"}: UsePyThread_tss_get{.interpreted-text role="c:func"} instead.PyThread_delete_key_value{.interpreted-text role="c:func"}: UsePyThread_tss_delete{.interpreted-text role="c:func"} instead.PyThread_ReInitTLS{.interpreted-text role="c:func"}: Unneeded since Python 3.7.
Build Changes
arm64-apple-iosandarm64-apple-ios-simulatorare both now11{.interpreted-text role="pep"} tier 3 platforms. (PEP 730 <whatsnew313-platform-support>{.interpreted-text role="ref"} written and implementation contributed by Russell Keith-Magee in114099{.interpreted-text role="gh"}.)aarch64-linux-androidandx86_64-linux-androidare both now11{.interpreted-text role="pep"} tier 3 platforms. (PEP 738 <whatsnew313-platform-support>{.interpreted-text role="ref"} written and implementation contributed by Malcolm Smith in116622{.interpreted-text role="gh"}.)wasm32-wasiis now a11{.interpreted-text role="pep"} tier 2 platform. (Contributed by Brett Cannon in115192{.interpreted-text role="gh"}.)wasm32-emscriptenis no longer a11{.interpreted-text role="pep"} supported platform. (Contributed by Brett Cannon in115192{.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 in89886{.interpreted-text role="gh"} and by Victor Stinner in112090{.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 in105875{.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, see113141{.interpreted-text role="gh"} for details. (Contributed by Dino Viehland in109914{.interpreted-text role="gh"}.) - The
configure{.interpreted-text role="file"} option--with-system-libmpdec{.interpreted-text role="option"} now defaults toyes. The bundled copy oflibmpdecwill 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 anddebug build <debug-build>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in108634{.interpreted-text role="gh"}.) - On POSIX systems, the pkg-config (
.pc) filenames now include the ABI flags. For example, the free-threaded build generatespython-3.13t.pcand the debug build generatespython-3.13d.pc. - The
errno,fcntl,grp,md5,pwd,resource,termios,winsound,_ctypes_test,_multiprocessing.posixshmem,_scproxy,_stat,_statistics,_testconsole,_testimportmultipleand_uuidC extensions are now built with thelimited C API <limited-c-api>{.interpreted-text role="ref"}. (Contributed by Victor Stinner in85283{.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 oflocals{.interpreted-text role="func"} andf_locals <frame.f_locals>{.interpreted-text role="attr"}:- Calling
locals{.interpreted-text role="func"} in anoptimized 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 asexecandeval) must be passed an explicit namespace to access their results in an optimized scope. (Changed as part of667{.interpreted-text role="pep"}.) - Calling
locals{.interpreted-text role="func"} from a comprehension at module or class scope (including viaexecoreval) 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 implementing709{.interpreted-text role="pep"}. (Changed as part of667{.interpreted-text role="pep"}.) - Accessing
FrameType.f_locals <frame.f_locals>{.interpreted-text role="attr"} in anoptimized 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 withdictor the proxy's.copy()method. (Changed as part of667{.interpreted-text role="pep"}.)
- Calling
functools.partial{.interpreted-text role="class"} now emits aFutureWarning{.interpreted-text role="exc"} when used as a method. The behavior will change in future Python versions. Wrap it instaticmethod{.interpreted-text role="func"} if you want to preserve the old behavior. (Contributed by Serhiy Storchaka in121027{.interpreted-text role="gh"}.)An
OSError{.interpreted-text role="exc"} is now raised bygetpass.getuser{.interpreted-text role="func"} for any failure to retrieve a username, instead ofImportError{.interpreted-text role="exc"} on non-Unix platforms orKeyError{.interpreted-text role="exc"} on Unix platforms where the password database is empty.The value of the
!mode{.interpreted-text role="attr"} attribute ofgzip.GzipFile{.interpreted-text role="class"} is now a string ('rb'or'wb') instead of an integer (1or2). The value of the!mode{.interpreted-text role="attr"} attribute of the readable file-like object returned byzipfile.ZipFile.open{.interpreted-text role="meth"} is now'rb'instead of'r'. (Contributed by Serhiy Storchaka in115961{.interpreted-text role="gh"}.)mailbox.Maildir{.interpreted-text role="class"} now ignores files with a leading dot (.). (Contributed by Zackery Spytz in65559{.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 returnsTrueif 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.hno 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 theHAVE_IEEEFP_Hmacro. (Contributed by Victor Stinner in108765{.interpreted-text role="gh"}.)Python.hno 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 in108765{.interpreted-text role="gh"}.)On Windows,
Python.hno 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, andsize_tandptrdiff_ttypes. Including<stddef.h>explicitly was already needed by all other platforms, theHAVE_STDDEF_Hmacro is only defined on Windows. (Contributed by Victor Stinner in108765{.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 in85283{.interpreted-text role="gh"}.)The old trashcan macros
Py_TRASHCAN_SAFE_BEGINandPy_TRASHCAN_SAFE_ENDwere removed. They should be replaced by the new macrosPy_TRASHCAN_BEGINandPy_TRASHCAN_END.A
tp_deallocfunction 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_BEGINhas 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 in105111{.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 anoptimized scope{.interpreted-text role="term"} have changed. New dict entries added this way will now only be visible to subsequentPyEval_GetLocals{.interpreted-text role="c:func"} calls in that frame, asPyFrame_GetLocals{.interpreted-text role="c:func"},locals{.interpreted-text role="func"}, andFrameType.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 toPyEval_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 anoptimized 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. withPyDict_Copy{.interpreted-text role="c:func"}), or by calling the newPyEval_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, whenPyFrame_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 thatPyFrame_GetLocals{.interpreted-text role="c:func"} returns a write-through proxy foroptimized scopes <optimized scope>{.interpreted-text role="term"}.
- The effects of mutating the dictionary returned from
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"} orPyDict_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"} orPyEval_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"} orPyTime_MonotonicRaw{.interpreted-text role="c:func"};_PyTime_GetPerfCounter():PyTime_PerfCounter{.interpreted-text role="c:func"} orPyTime_PerfCounterRaw{.interpreted-text role="c:func"};_PyTime_GetSystemClock():PyTime_Time{.interpreted-text role="c:func"} orPyTime_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, beforesite.pyis executed. (Contributed by Łukasz Langa in110769{.interpreted-text role="gh"}.)