What's new in Python 3.15
Editor
Hugo van Kemenade
* 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.)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.15, compared to 3.14. Python 3.15 was released on 9 October 2026. For full details, see the changelog <changelog>.
790 -- Python 3.15 release schedule
Summary -- Release highlights
Python 3.15 is the latest 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 lazy imports <whatsnew315-lazy-imports>, frozendict <whatsnew315-frozendict> and sentinel <whatsnew315-sentinel> builtins, UTF-8 as the default encoding <whatsnew315-utf8-default>, unpacking in comprehensions <whatsnew315-unpacking-in-comprehensions>, and a stable ABI for free-threaded builds <whatsnew315-abi3t>.
The library changes include a new profiling package <whatsnew315-profiling-package> with Tachyon <whatsnew315-sampling-profiler>, a high-frequency statistical sampling profiler, more color <whatsnew315-more-color> in command-line output, as well as the usual deprecations and removals, and improvements in user-friendliness and correctness.
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> and Language Reference <reference-index>. 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.15 for guidance on upgrading from earlier versions of Python.
Interpreter improvements:
661:Add sentinel built-in type <whatsnew315-sentinel>686:Python now uses UTF-8 as the default encoding <whatsnew315-utf8-default>798:Unpacking in comprehensions <whatsnew315-unpacking-in-comprehensions>810:Explicit lazy imports for faster startup times <whatsnew315-lazy-imports>814:Add frozendict built-in type <whatsnew315-frozendict>829:Package startup configuration files <whatsnew315-startup-files>The experimental JIT compiler has been significantly upgraded <whatsnew315-jit>Improved error messages <whatsnew315-improved-error-messages>
Significant improvements in the standard library:
799:A dedicated profiling package for organizing Python profiling tools <whatsnew315-profiling-package>799:Tachyon: High-frequency statistical sampling profiler <whatsnew315-sampling-profiler>More color <whatsnew315-more-color>
New typing features:
728:TypedDict with typed extra items <whatsnew315-typeddict>747:Annotating type forms with TypeForm <whatsnew315-typeform>800:Disjoint bases in the type system <whatsnew315-disjoint-base>
C API improvements:
782:A new PyBytesWriter C API to create a Python bytes object <whatsnew315-pybyteswriter>788:Protection against finalization in the C API <whatsnew315-c-api-interpreter-finalization>803,820 <820>,793 <793>:Stable ABI for free-threaded builds <whatsnew315-abi3t>and related C API
Build changes:
831:Frame pointers are enabled by default for improved system-level observability <whatsnew315-frame-pointers>
Release changes:
The official Windows 64-bit binaries now use the tail-calling interpreter <whatsnew315-windows-tail-calling-interpreter>- The official macOS binaries now install free-threading support by default
New features
810: Explicit lazy imports
Large Python applications often suffer from slow startup times. A significant contributor to this problem is the import system: when a module is imported, Python must locate the file, read it from disk, compile it to bytecode, and execute all top-level code. For applications with deep dependency trees, this process can take seconds, even when most of the imported code is never actually used during a particular run.
Developers have worked around this by moving imports inside functions, using importlib to load modules on demand, or restructuring code to avoid unnecessary dependencies. These approaches work but make code harder to read and maintain, scatter import statements throughout the codebase, and require discipline to apply consistently.
Python now provides a cleaner solution through explicit lazy imports using the new lazy soft keyword. When you mark an import as lazy, Python defers the actual module loading until the imported name is first used. This gives you the organizational benefits of declaring all imports at the top of the file while only paying the loading cost for modules you actually use.
The lazy keyword works with both import and from ... import statements. When you write lazy import heavy_module, Python does not immediately load the module. Instead, it creates a lightweight proxy object. The actual module loading happens transparently when you first access the name:
lazy import json
lazy from pathlib import Path
print("Starting up...") # json and pathlib are not fully imported yet
data = json.loads('{"key": "value"}') # json gets fully imported here
p = Path(".") # pathlib gets fully imported here
This mechanism is particularly useful for applications that import many modules at the top level but may only use a subset of them in any given run. The deferred loading reduces startup latency without requiring code restructuring or conditional imports scattered throughout the codebase.
In the case where loading a lazily imported module fails (for example, if the module does not exist), Python raises the exception at the point of first use rather than at import time. The associated traceback includes both the location where the name was accessed and the original import statement, making it straightforward to diagnose and debug the failure.
For cases where you want to enable lazy loading globally without modifying source code, Python provides the -X lazy_imports <-X> command-line option and the PYTHON_LAZY_IMPORTS environment variable. Both accept two values: all makes all imports lazy by default, and normal (the default) respects the lazy keyword in source code. The sys.set_lazy_imports and sys.get_lazy_imports functions allow changing and querying this mode at runtime.
For more selective control, sys.set_lazy_imports_filter accepts a callable that determines whether a specific module should be loaded lazily. The filter receives three arguments: the importing module's name (or None), the imported module's name, and the fromlist (or None for regular imports). It should return True to allow the import to be lazy, or False to force eager loading. This allows patterns like making only your own application's modules lazy while keeping third-party dependencies eager:
import sys
def myapp_filter(importing, imported, fromlist):
return imported.startswith("myapp.")
sys.set_lazy_imports_filter(myapp_filter)
sys.set_lazy_imports("all")
import myapp.slow_module # lazy (matches filter)
import json # eager (does not match filter)
The proxy type itself is available as types.LazyImportType for code that needs to detect lazy imports programmatically.
There are some restrictions on where the lazy keyword can be used. Lazy imports are only permitted at module scope; using lazy inside a function, class body, or try/except/finally block raises a SyntaxError. Neither star imports nor future imports can be lazy (lazy from module import * and lazy from __future__ import ... both raise SyntaxError).
For code that cannot use the lazy keyword directly (for example, when supporting Python versions older than 3.15 while still using lazy imports on 3.15+), a module can define ~module.__lazy_modules__ as a container of fully qualified module name strings. Regular import statements for those modules are then treated as lazy, with the same semantics as the lazy keyword:
__lazy_modules__ = ["json", "pathlib"]
import json # lazy
import os # still eager
(Contributed by Pablo Galindo Salgado and Dino Viehland in 142349.)
810 for the full specification and rationale.
814: Add frozendict built-in type
A new immutable type, frozendict, is added to the builtins module. It does not allow modification after creation. A !frozendict is not a subclass of dict; it inherits directly from object. A !frozendict is hashable as long as all of its keys and values are hashable. A !frozendict preserves insertion order, but comparison does not take order into account.
For example:
>>> a = frozendict(x=1, y=2)
>>> a
frozendict({'x': 1, 'y': 2})
>>> a['z'] = 3
Traceback (most recent call last):
File "<python-input-2>", line 1, in <module>
a['z'] = 3
~^^^^^
TypeError: 'frozendict' object does not support item assignment
>>> b = frozendict(y=2, x=1)
>>> hash(a) == hash(b)
True
>>> a == b
True
The following standard library modules have been updated to accept !frozendict: copy, decimal, json, marshal, plistlib (only for serialization), pickle, pprint and xml.etree.ElementTree.
eval and exec accept !frozendict for globals, and type and str.maketrans accept !frozendict for dict.
Code checking for dict type using isinstance(arg, dict) can be updated to isinstance(arg, (dict, frozendict)) to accept also the !frozendict type, or to isinstance(arg, collections.abc.Mapping) to accept also other mapping types such as ~types.MappingProxyType.
(Contributed by Victor Stinner and Donghee Na in 141510.)
814 for the full specification and rationale.
661: Add sentinel built-in type
A new sentinel type is added to the builtins module for creating unique sentinel values with a concise representation. Sentinel objects preserve identity when copied, support use in type expressions with the | operator, and can be pickled when they are importable by module and name.
(Contributed by Jelle Zijlstra in 148829; PEP 661 written by Tal Einat.)
661 for further details.
799: A dedicated profiling package
A new profiling module has been added to organize Python's built-in profiling tools under a single, coherent namespace. This module contains:
profiling.tracing: deterministic function-call tracing (relocated fromcProfile).profiling.sampling: a new statistical sampling profiler (named Tachyon).
The cProfile module remains as an alias for backwards compatibility. The profile module is deprecated and will be removed in Python 3.17.
(Contributed by Pablo Galindo and László Kiss Kollár in 138122.)
799 for further details.
Tachyon: High-frequency statistical sampling profiler
A new statistical sampling profiler (Tachyon) has been added as profiling.sampling. This profiler enables low-overhead performance analysis of running Python processes without requiring code modification or process restart.
Unlike deterministic profilers (such as profiling.tracing) that instrument every function call, the sampling profiler periodically captures stack traces from running processes. This approach provides virtually zero overhead while achieving sampling rates of up to 1,000,000 Hz, making it the fastest sampling profiler available for Python (at the time of its contribution) and ideal for debugging performance issues in production environments. This capability is particularly valuable for debugging performance issues in production systems where traditional profiling approaches would be too intrusive.
Key features include:
- Zero-overhead profiling: Attach to any running Python process without affecting its performance. Ideal for production debugging where you can't afford to restart or slow down your application.
- No code modification required: Profile existing applications without restart. Simply point the profiler at a running process by PID and start collecting data.
- Flexible target modes:
- Profile running processes by PID (
attach) - attach to already-running applications - Run and profile scripts directly (
run) - profile from the very start of execution - Execute and profile modules (
run -m) - profile packages run aspython -m module - Capture a one-shot snapshot of a running process (
dump) - print a traceback-style stack of every thread (or all asyncio tasks with--async-aware). Useful for investigating hung processes.
- Profile running processes by PID (
- Multiple profiling modes: Choose what to measure based on your performance investigation:
- Wall-clock time (
--mode wall, default): Measures real elapsed time including I/O, network waits, and blocking operations. Use this to understand where your program spends calendar time, including when waiting for external resources. - CPU time (
--mode cpu): Measures only active CPU execution time, excluding I/O waits and blocking. Use this to identify CPU-bound bottlenecks and optimize computational work. - GIL-holding time (
--mode gil): Measures time spent holding Python's Global Interpreter Lock. Use this to identify which threads dominate GIL usage in multi-threaded applications. - Exception handling time (
--mode exception): Captures samples only from threads with an active exception. Use this to analyze exception handling overhead.
- Wall-clock time (
- Thread-aware profiling: Option to profile all threads (
-a) or just the main thread, essential for understanding multi-threaded application behavior. - Multiple output formats: Choose the visualization that best fits your workflow:
--pstats: Detailed tabular statistics compatible withpstats. Shows function-level timing with direct and cumulative samples. Best for detailed analysis and integration with existing Python profiling tools.--collapsed: Generates collapsed stack traces (one line per stack). This format is specifically designed for creating flame graphs with external tools like Brendan Gregg's FlameGraph scripts or speedscope.--flamegraph: Generates a self-contained interactive HTML flame graph using D3.js. Opens directly in your browser for immediate visual analysis. Flame graphs show the call hierarchy where width represents time spent, making it easy to spot bottlenecks at a glance.--gecko: Generates Gecko Profiler format compatible with Firefox Profiler. Upload the output to Firefox Profiler for advanced timeline-based analysis with features like stack charts, markers, and network activity.--heatmap: Generates an interactive HTML heatmap visualization with line-level sample counts. Creates a directory with per-file heatmaps showing exactly where time is spent at the source code level.
- Live interactive mode: Real-time TUI profiler with a top-like interface (
--live). Monitor performance as your application runs with interactive sorting and filtering. - Async-aware profiling: Profile async/await code with task-based stack reconstruction (
--async-aware). See which coroutines are consuming time, with options to show only running tasks or all tasks including those waiting. - Opcode-level profiling: Gather bytecode opcode information for instruction-level profiling (
--opcodes). Shows which bytecode instructions are executing, including specializations from the adaptive interpreter.
See profiling.sampling for the complete documentation, including all available output formats, profiling modes, and configuration options.
(Contributed by Pablo Galindo and László Kiss Kollár in 135953 and 138122.)
831: Frame pointers enabled by default
CPython is now built with frame pointers by default on platforms that support them. This uses the compiler flags -fno-omit-frame-pointer and -mno-omit-leaf-frame-pointer, making native stack unwinding faster and more reliable for system profilers, debuggers, crash analysis tools, and eBPF-based observability tools.
The flags are exposed through sysconfig, so extension modules built by tools that consume Python's build configuration inherit frame pointers by default. This propagation is intentional: mixed Python/native profiling needs an unbroken frame-pointer chain through the interpreter, extension modules, embedding applications, and native libraries.
[!IMPORTANT] Third-party build backends and native build systems should preserve these flags when they consume Python's
sysconfigvalues. Build systems that compile C, C++, Rust, or other native code without inheriting Python's compiler flags should enable equivalent frame-pointer flags themselves. A single native component built without frame pointers can break stack unwinding for the whole Python process.
(Contributed by Pablo Galindo Salgado and Savannah Ostrowski in 149201; PEP 831 written by Pablo Galindo Salgado, Ken Jin, Savannah Ostrowski, and Diego Russo.)
831 for further details.
798: Unpacking in comprehensions
List, set, and dictionary comprehensions, as well as generator expressions, now support unpacking with * and **. This extends the unpacking syntax from 448 to comprehensions, providing a new syntax for combining an arbitrary number of iterables or dictionaries into a single flat structure. This new syntax is a direct alternative to nested comprehensions, itertools.chain, and itertools.chain.from_iterable. For example:
>>> lists = [[1, 2], [3, 4], [5]]
>>> [*L for L in lists] # equivalent to [x for L in lists for x in L]
[1, 2, 3, 4, 5]
>>> sets = [{1, 2}, {2, 3}, {3, 4}]
>>> {*s for s in sets} # equivalent to {x for s in sets for x in s}
{1, 2, 3, 4}
>>> dicts = [{'a': 1}, {'b': 2}, {'a': 3}]
>>> {**d for d in dicts} # equivalent to {k: v for d in dicts for k,v in d.items()}
{'a': 3, 'b': 2}
Generator expressions can similarly use unpacking to yield values from multiple iterables:
>>> gen = (*L for L in lists) # equivalent to (x for L in lists for x in L)
>>> list(gen)
[1, 2, 3, 4, 5]
This change also extends to asynchronous generator expressions, such that, for example, (*a async for a in agen()) is equivalent to (x async for a in agen() for x in a).
(Contributed by Adam Hartz in 143055.)
798 for further details.
829: Package startup configuration files
Loaded by the site module when -S is not given, .pth files <site-pth-files> can contain lines that both extend sys.path and execute arbitrary code when the line starts with import (followed by a space or tab). The latter functionality can be problematic, since it is difficult to know exactly what gets executed when Python starts up.
As a step towards improving the ability to audit pre-start executable code, Python 3.15 introduces .start files <site-start-files> which contain entry point specifications of the form pkg.mod:callable where pkg.mod is the import path to the given callable. When Python starts up, the callable is located and called with no arguments.
import lines in .pth files are silently deprecated. When a matching .start file is found, import lines in .pth files are ignored. There is no change to sys.path extension lines in .pth files.
The site module also provides site.StartupState to batch startup processing for multiple site directories, ensuring all static path extensions are applied before any startup code is executed. site.main uses an instance of this class implicitly to batch process all startup configuration files during normal interpreter startup. Callers needing the same batching behavior can build a ~site.StartupState directly and drive it with ~site.StartupState.addsitedir, ~site.StartupState.addusersitepackages, and ~site.StartupState.addsitepackages, then call ~site.StartupState.process once at the end of the batch.
(Contributed by Barry Warsaw in 148641 and 150228.)
803: Stable ABI for free-threaded builds
C extensions that target the Stable ABI <stable-abi> can now be compiled for the new Stable ABI for Free-Threaded Builds (also known as abi3t), which makes them compatible with free-threaded builds <free-threaded build> of CPython. This usually requires some non-trivial changes to the source code; specifically:
- Switching to API introduced in
697(Python 3.12), such as negative~PyType_Spec.basicsizeandPyObject_GetTypeData, rather than makingPyObjectpart of the instance struct; and - Switching from a
PyInit_function to a new export hook,PyModExport_* <PyModExport_modulename>, introduced for this purpose in793, with a newPySlotstructure introduced in820.
Note that Stable ABI does not offer all the functionality that CPython has to offer. Extensions that cannot switch to abi3t should continue to build for the existing Stable ABI (abi3) and the version-specific ABI for free-threading (cp315t) separately.
Stable ABI for Free-Threaded Builds should typically be selected in a build tool. Tools with abi3t support include meson-python, scikit-build-core, and Maturin; see abi3t-migration-build for links to their documentation on abi3t builds. If your build tool does not support abi3t, compile for cp315t separately. If not using a build tool -- or when writing such a tool -- you can select abi3t by setting the macro !Py_TARGET_ABI3T as discussed in abi3-compiling.
A practical migration guide <abi3t-migration-howto> for switching to abi3t is available. The community-maintained Python Free-Threading Guide provides examples of building and testing abi3t wheels.
803 for further details.
788: Protecting the C API from interpreter finalization
In the C API, interpreter finalization <interpreter shutdown> can be problematic for many extensions, because attaching <attached thread state> a thread state will permanently hang the thread, resulting in deadlocks and other spurious issues. Additionally, it has historically been impossible to safely check whether an interpreter is alive before using it, leading to crashes when a thread concurrently deletes an interpreter while another thread is trying to attach to it.
There are now several new suites of APIs to circumvent these problems:
Interpreter guards <interpreter-guards>, which prevent an interpreter from finalizing.Interpreter views <interpreter-views>, which allow thread-safe access to an interpreter that may be concurrently finalizing or deleted.New APIs <c-api-attach-detach>to automatically attach and detach thread states that come with built-in protection against finalization.
In addition, APIs in the PyGILState family (most notably PyGILState_Ensure and PyGILState_Release) have been soft deprecated. There is no plan to remove them, and existing code will continue to work, but there will be no new PyGILState APIs in future versions of Python.
(Contributed by Peter Bierma in 149101.)
788 for further details.
Improved error messages
-
The interpreter now provides more helpful suggestions in
AttributeErrorexceptions when accessing an attribute on an object that does not exist, but a similar attribute is available through one of its members.For example, if the object has an attribute that itself exposes the requested name, the error message will suggest accessing it via that inner attribute:
from dataclasses import dataclass from math import pi @dataclass class Circle: radius: float @property def area(self) -> float: return pi * self.radius**2 class Container: def __init__(self, inner: Circle) -> None: self.inner = inner circle = Circle(radius=4.0) container = Container(circle) print(container.area)Running this code now produces a clearer suggestion:
Traceback (most recent call last): File "example.py", line 18, in <module> print(container.area) ^^^^^^^^^^^^^^ AttributeError: 'Container' object has no attribute 'area'. Did you mean '.inner.area' instead of '.area'? -
When an
AttributeErroron a builtin type has no close match via Levenshtein distance, the error message now checks a static table of common method names from other languages (JavaScript, Java, Ruby, C#) and suggests the Python equivalent:>>> [1, 2, 3].push(4) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'list' object has no attribute 'push'. Did you mean '.append'?
>>> 'hello'.toUpperCase() # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'str' object has no attribute 'toUpperCase'. Did you mean '.upper'?
When the Python equivalent is a language construct rather than a method, the hint describes the construct directly:
>>> {}.put("a", 1) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'dict' object has no attribute 'put'. Use d[k] = v.
When a mutable method is called on an immutable type, the hint suggests the mutable counterpart:
>>> (1, 2, 3).append(4) # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'tuple' object has no attribute 'append'. Did you mean to use a 'list' object?
These hints also work for subclasses of builtin types.
(Contributed by Matt Van Horn in
146406.) -
The interpreter now tries to provide a suggestion when
delattrfails due to a missing attribute. When an attribute name that closely resembles an existing attribute is used, the interpreter will suggest the correct attribute name in the error message. For example:>>> class A: ... pass >>> a = A() >>> a.abcde = 1 >>> del a.abcdf # doctest: +ELLIPSIS Traceback (most recent call last): ... AttributeError: 'A' object has no attribute 'abcdf'. Did you mean: 'abcde'?
(Contributed by Nikita Sobolev and Pranjal Prajapati in
136588.) -
Several error messages incorrectly using the term "argument" have been corrected. (Contributed by Stan Ulbrych in
133382.)
Other language changes
-
Python now uses UTF-8 as the default encoding, independent of the system's environment. This means that I/O operations without an explicit encoding, for example,
open('flying-circus.txt'), will use UTF-8. UTF-8 is a widely-supported Unicode character encoding that has become a de facto standard for representing text, including nearly every webpage on the internet, many common file formats, programming languages, and more.This only applies when no
encodingargument is given. For best compatibility between versions of Python, ensure that an explicitencodingargument is always provided. Theopt-in encoding warning <io-encoding-warning>can be used to identify code that may be affected by this change. The specialencoding='locale'argument uses the current locale encoding, and has been supported since Python 3.10.To retain the previous behaviour, Python's UTF-8 mode may be disabled with the
PYTHONUTF8=0 <PYTHONUTF8>environment variable or the-X utf8=0 <-X>command-line option.(Contributed by Adam Turner in
133711; PEP 686 written by Inada Naoki.)686for further details. -
The interpreter help (such as
python --help) is now in color. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148766.) -
Unraisable exceptions are now highlighted with color by default. This can be controlled by
environment variables <using-on-controlling-color>. (Contributed by Peter Bierma in134170.) -
More color in
argparse <whatsnew315-color-argparse>,ast <whatsnew315-color-ast>,calendar <whatsnew315-color-calendar>,difflib <whatsnew315-color-difflib>,http.server <whatsnew315-color-http.server>,pickletools <whatsnew315-color-pickletools>,PyREPL tab completion <whatsnew315-pyrepl-completion>,python --help <whatsnew315-color-interpreter-help>,sqlite3 <whatsnew315-color-sqlite3>,timeit <whatsnew315-color-timeit>,tokenize <whatsnew315-color-tokenize>,unraisable exceptions <whatsnew315-color-exceptions>andstdlib(ast, compileall, doctest, gzip, inspect, json.tool, pdb, profiling.sampling, random, regrtest, sqlite3, timeit, tokenize, trace, unittest, uuid, zipapp, zipfile) CLI help. -
The
~object.__repr__ofImportErrorandModuleNotFoundErrornow shows "name" and "path" asname=<name>andpath=<path>if they were given as keyword arguments at construction time. (Contributed by Serhiy Storchaka, Oleg Iarygin, and Yoav Nir in74185.) -
The
~object.__dict__and!__weakref__descriptors now use a single descriptor instance per interpreter, shared across all types that need them. This speeds up class creation, and helps avoid reference cycles. (Contributed by Petr Viktorin in135228.) -
The
-Woption and thePYTHONWARNINGSenvironment variable can now specify regular expressions instead of literal strings to match the warning message and the module name, if the corresponding field starts and ends with a forward slash (/). (Contributed by Serhiy Storchaka in134716.) -
Functions that take timestamp or timeout arguments now accept any real numbers (such as
~decimal.Decimaland~fractions.Fraction), not only integers or floats, although this does not improve precision. (Contributed by Serhiy Storchaka in67795.)
-
Added
bytearray.take_bytes(n=None, /) <bytearray.take_bytes>to take bytes out of abytearraywithout copying. This enables optimizing code which must returnbytesafter working with a mutable buffer of bytes such as data buffering, network protocol parsing, encoding, decoding, and compression. Common code patterns which can be optimized with~bytearray.take_bytesare listed below.Suggested optimizing refactors Description Old New Return bytesafter working withbytearrayEmpty a buffer getting the bytes Split a buffer at a specific separator Split a buffer at a specific separator; discard after the separator (Contributed by Cody Maloney in
139871.) -
Many functions related to compiling or parsing Python code, such as
compile,ast.parse,symtable.symtable, andimportlib.abc.InspectLoader.source_to_code, now allow the module name to be passed. It is needed to unambiguouslyfilter <warning-filter>syntax warnings by module name. (Contributed by Serhiy Storchaka in135801.) -
Allowed defining the __dict__ and __weakref__
__slots__ <slots>for any class. (Contributed by Serhiy Storchaka in41779.) -
Allowed defining any
__slots__ <slots>for a class derived fromtuple(including classes created bycollections.namedtuple). (Contributed by Serhiy Storchaka in41779.) -
The
slicetype now supports subscription, making it ageneric type. (Contributed by James Hilton-Balfe in128335.) -
The class
memoryviewnow supports thefloat complexanddouble complexC types: formatting characters'Zf'and'Zd'respectively. (Contributed by Victor Stinner in146151and148675.) -
Allow the count argument of
bytes.replaceto be a keyword. (Contributed by Stan Ulbrych in147856.) -
Unary plus is now accepted in
matchliteral patterns, mirroring the existing support for unary minus. (Contributed by Bartosz Sławecki in145239.) -
The import system now acquires per-module locks in hierarchical order (parent packages before their submodules). This fixes a long-standing deadlock where one thread importing
pkg.suband another importingpkg.sub.modcould each block the other whenpkg/sub/__init__.pyimportspkg.sub.mod. (Contributed by Gregory P. Smith in83065.) -
File names of Stable ABI extensions that use the
.sosuffix may now include a multiarch tuple, for example,foo.abi3-x86-64-linux-gnu.so. This permits stable ABI extensions for multiple architectures to be co-installed into the same directory, without clashing with each other, as regular dynamic extensions do. (Contributed by Stefano Rivera in122931.) -
The
__cached__attribute on modules, which was deprecated since version 3.13, is no longer set or taken into consideration by the import system or standard library. Use__spec__.cached <importlib.machinery.ModuleSpec.cached>instead. (Contributed by Brett Cannon in97879.)Note that the
~module.__loader__and~module.__package__attributes are also deprecated and scheduled for removal.
Default interactive shell
- Tab completions are now colored by object kind, based on
fancycompleter. SetPYTHON_BASIC_COMPLETERto fall back torlcompleter. Color can also be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Antonio Cuni and Pablo Galindo in130472.) - Tab completion now suggests module attributes in
from ... importstatements. Attributes can only be suggested once the module is imported, sostdlibmodules are imported automatically, while for other modules the completer offers to import them whenTabis pressed a second time. (Contributed by Loïc Simon and Pablo Galindo in140870.)
New modules
math.integer
This module provides access to the mathematical functions for integer arguments (791). (Contributed by Serhiy Storchaka in 81313.)
Improved modules
argparse
- The
~argparse.BooleanOptionalActionaction now supports single-dash long options and alternate prefix characters. (Contributed by Serhiy Storchaka in138525.) - Changed the suggest_on_error parameter of
argparse.ArgumentParserto default toTrue. This enables suggestions for mistyped arguments by default. (Contributed by Jakob Schluse in140450.) - Added backtick markup support in
~argparse.ArgumentParserdescription and epilog text to highlight inline code when color output is enabled. (Contributed by Savannah Ostrowski in142390.) - Extended backtick markup to argument
helptext and added support for double backticks (RST inline-literal style). (Contributed by Hugo van Kemenade in149375.)
array
- Support the
float complexanddouble complexC types: formatting characters'Zf'and'Zd'respectively. (Contributed by Victor Stinner in146151and148675.) - Support half-floats (16-bit IEEE 754 binary interchange format): formatting character
'e'. (Contributed by Sergey B Kirpichev in146238.) - The
array.typecodestype changed fromstrtotupleto support type codes longer than 1 character (ZfandZd). (Contributed by Victor Stinner in148675.)
ast
- Add color parameter to
~ast.dump. IfTrue, the returned string is syntax highlighted using ANSI escape sequences. IfFalse(the default), colored output is always disabled. (Contributed by Stan Ulbrych in148981.) - The
command-line <ast-cli>output is now syntax highlighted by default. This can becontrolled using environment variables <using-on-controlling-color>. (Contributed by Stan Ulbrych in148981.)
asyncio
- Added
TaskGroup.cancel <asyncio.TaskGroup.cancel>to allow early termination of a task group, for instance, when the goal of the tasks has been achieved or their services are no longer needed. Previously this would involve unintuitive boilerplate such as an extra task raising a custom exception which is then suppressed as it exits the task group. (Contributed by John Belmonte in127214.)
base64
- Added the pad parameter in
~base64.z85encode. (Contributed by Hauke Dämpfling in143103.) - Added the padded parameter in
~base64.b32encode,~base64.b32decode,~base64.b32hexencode,~base64.b32hexdecode,~base64.b64encode,~base64.b64decode,~base64.urlsafe_b64encode, and~base64.urlsafe_b64decode. (Contributed by Serhiy Storchaka in73613.) - Added the wrapcol parameter in
~base64.b16encode,~base64.b32encode,~base64.b32hexencode,~base64.b64encode,~base64.b85encode, and~base64.z85encode. (Contributed by Serhiy Storchaka in143214and146431.) - Added the ignorechars parameter in
~base64.b16decode,~base64.b32decode,~base64.b32hexdecode,~base64.b64decode,~base64.b85decode, and~base64.z85decode. (Contributed by Serhiy Storchaka in144001and146431.) - Added the canonical parameter in
~base64.b32decode,~base64.b32hexdecode,~base64.b64decode,~base64.a85decode,~base64.b85decode, and~base64.z85decode, to reject encodings with non-zero padding bits or other non-canonical forms. (Contributed by Gregory P. Smith in146311.)
binascii
-
Added functions for Base32 encoding:
~binascii.b2a_base32and~binascii.a2b_base32
(Contributed by James Seo in
146192.) -
Added functions for Ascii85, Base85, and Z85 encoding:
~binascii.b2a_ascii85and~binascii.a2b_ascii85~binascii.b2a_base85and~binascii.a2b_base85
(Contributed by James Seo and Serhiy Storchaka in
101178.) -
Added the padded parameter in
~binascii.b2a_base32,~binascii.a2b_base32,~binascii.b2a_base64, and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in73613.) -
Added the wrapcol parameter in
~binascii.b2a_base64. (Contributed by Serhiy Storchaka in143214.) -
Added the alphabet parameter in
~binascii.b2a_base64and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in145980.) -
Added the ignorechars parameter in
~binascii.a2b_hex,~binascii.unhexlify, and~binascii.a2b_base64. (Contributed by Serhiy Storchaka in144001and146431.) -
Added the canonical parameter in
~binascii.a2b_base64, to reject encodings with non-zero padding bits. (Contributed by Gregory P. Smith in146311.)
calendar
calendar'scommand-line <calendar-cli>text output has more color. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148352.)- The
calendar'scommand-line <calendar-cli>HTML output now accepts the year-month option:python -m calendar -t html 2009 06. (Contributed by Pål Grønås Drange in140212.) - Calendar pages generated by the
calendar.HTMLCalendarclass now support dark mode and have been migrated to the HTML5 standard for improved accessibility. (Contributed by Jiahao Li and Hugo van Kemenade in137634.)
collections
- Added
!collections.Counter.__xor__and!collections.Counter.__ixor__to compute the symmetric difference between~collections.Counterobjects. (Contributed by Raymond Hettinger in138682.)
concurrent.futures
- Improved error reporting when a child process in a
concurrent.futures.ProcessPoolExecutorterminates abruptly. The resulting traceback will now tell you the PID and exit code of the terminated process. (Contributed by Jonathan Berg in139486.)
contextlib
- Added support for arbitrary descriptors
!__enter__,!__exit__,!__aenter__, and!__aexit__in~contextlib.ExitStackandcontextlib.AsyncExitStack, for consistency with thewithandasync withstatements. (Contributed by Serhiy Storchaka in144386.) ~contextlib.ContextDecoratorand~contextlib.AsyncContextDecorator(and therefore~contextlib.contextmanagerand~contextlib.asynccontextmanagerused as decorators) now detect generator functions, coroutine functions, and asynchronous generator functions and keep the context manager open across iteration or await. Previously the context manager exited as soon as the generator or coroutine object was created. (Contributed by Alex Grönholm & Gregory P. Smith in125862.)
ctypes
- Change the
~ctypes._SimpleCData._type_of~ctypes.c_float_complex,~ctypes.c_double_complexand~ctypes.c_longdouble_complexfromF,DandGtoZf,ZdandZgfor compatibility with NumPy. (Contributed by Victor Stinner in148675.)
dataclasses
- Annotations for generated
__init__methods no longer include internal type names. (Contributed by David Ellis in137530.)
dbm
- Added new
!reorganizemethods todbm.dumbanddbm.sqlite3to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in134004.)
difflib
- Introduced the optional color parameter to
difflib.unified_diff, enabling color output similar togit diff. This can be controlled byenvironment variables <using-on-controlling-color>. (Contributed by Douglas Thor in133725.) - Improved the styling of HTML diff pages generated by the
difflib.HtmlDiffclass, and migrated the output to the HTML5 standard. (Contributed by Jiahao Li in134580.)
- Email generators now raise an error when an
.EmailMessagecannot be accurately flattened due to a non-ASCII email address (mailbox) in an address header. Options for supporting Email Address Internationalization (EAI) are discussed in.EmailPolicy.utf8. (Contributed by R David Murray and Mike Edmunds in122540.)
faulthandler
- Added the max_threads parameter in
faulthandler.enable,faulthandler.dump_traceback,faulthandler.dump_traceback_later, andfaulthandler.register. (Contributed by Eric Froemling in149085.)
functools
~functools.singledispatchmethodnow supports non-descriptorcallables. (Contributed by Serhiy Storchaka in140873.)~functools.singledispatchmethodnow dispatches on the second argument if it wraps a regular method and is called as a class attribute. (Contributed by Bartosz Sławecki in143535.)
gc
- Python 3.14.0-3.14.4 shipped with a new incremental garbage collector. However, due to a number of reports of significant memory pressure in production environments, it has been reverted back to the generational GC from 3.13. This is the GC now used in Python 3.14.5 and later and Python 3.15. (Contributed by Sergey Miryanov in
148726.)
hashlib
- Ensure that hash functions guaranteed to be always available exist as attributes of
hashlibeven if they will not work at runtime due to missing backend implementations. For instance,hashlib.md5will no longer raiseAttributeErrorif OpenSSL is not available and Python has been built without MD5 support. (Contributed by Bénédikt Tran in136929.)
http.client
- A new max_response_headers keyword-only parameter has been added to
~http.client.HTTPConnectionand~http.client.HTTPSConnectionconstructors. This parameter overrides the default maximum number of allowed response headers. (Contributed by Alexander Enrique Urieles Nieto in131724.)
http.server
- The logging of
~http.server.BaseHTTPRequestHandler, as used by thecommand-line interface <http-server-cli>, is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in146292.) - Added
~http.server.SimpleHTTPRequestHandler.default_content_typeand the--content-type <http.server --content-type>command-line option to allow customizing the defaultContent-Typeheader for files with unknown extensions. (Contributed by John Comeau and Hugo van Kemenade in113471.) - Add a new
extra_response_headerskeyword argument to~http.server.SimpleHTTPRequestHandlerto support custom headers in HTTP responses. (Contributed by Anton I. Sipos in135057.) - Add a
-H/--header <http.server --header>option to thepython -m http.servercommand-line interface to support custom headers in HTTP responses. (Contributed by Anton I. Sipos in135057.)
importlib.metadata
- Previously, when accessing a distribution metadata directory not containing a metadata file,
metadata()andDistribution.metadatawould return an emptyPackageMetadataobject as if the file was present but empty. Now, aMetadataNotFoundexception is raised. See importlib_metadata#493 for background and rationale and143387for rationale on the compatibility concerns. (Contributed by Jason R. Coombs.)
inspect
- Add parameters inherit_class_doc and fallback_to_class_doc for
~inspect.getdoc. (Contributed by Serhiy Storchaka in132686.)
json
- Add the array_hook parameter to
~json.loadand~json.loadsfunctions: allow a callback for JSON literal array types to customize Python lists in the resulting decoded object. Passing combinedfrozendictto object_pairs_hook parameter andtupleto array_hook will yield a deeply nested immutable Python structure representing the JSON data. (Contributed by Joao S. O. Bueno in146440.)
locale
~locale.setlocalenow supports language codes with@-modifiers.@-modifiers are no longer silently removed in~locale.getlocale, but included in the language code. (Contributed by Serhiy Storchaka in137729.)- Undeprecate the
locale.getdefaultlocalefunction. (Contributed by Victor Stinner in130796.)
math
- Add
math.isnormalandmath.issubnormalfunctions. (Contributed by Sergey B Kirpichev in132908.) - Add
math.fmax,math.fminandmath.signbitfunctions. (Contributed by Bénédikt Tran in135853.)
mimetypes
- Add more MIME types. (Contributed by Benedikt Johannes, Charlie Lin, Foolbar, Gil Forcada and John Franey in
144217,145720,140937,139959,145698,145718,145918, and144213.) - Rename
application/x-texinfotoapplication/texinfo. (Contributed by Charlie Lin in140165.) - Changed the MIME type for
.aifiles toapplication/pdf. (Contributed by Stan Ulbrych in141239.)
mmap
mmap.mmapnow has a trackfd parameter on Windows; if it isFalse, the file handle corresponding to fileno will not be duplicated. (Contributed by Serhiy Storchaka in78502.)- Added the
mmap.mmap.set_namemethod to annotate an anonymous memory mapping if Linux kernel supportsPR_SET_VMA_ANON_NAME <PR_SET_VMA(2const)>(Linux 5.17 or newer). (Contributed by Donghee Na in142419.)
os
- Add
os.statxon Linux kernel versions 4.11 and later with glibc versions 2.28 and later. (Contributed by Jeffrey Bosboom and Victor Stinner in83714.) os.makedirsfunction now has a parent_mode parameter that allows specifying the mode for intermediate directories. This can be used to match the behavior from Python 3.6 and earlier by passingparent_mode=mode. (Contributed by Zackery Spytz and Gregory P. Smith in86533.)
os.path
- Add support of the all-but-last mode in
~os.path.realpath. (Contributed by Serhiy Storchaka in71189.) - The strict parameter to
os.path.realpathaccepts a new value,os.path.ALLOW_MISSING. If used, errors other thanFileNotFoundErrorwill be re-raised; the resulting path can be missing but it will be free of symlinks. (Contributed by Petr Viktorin for2025-4517.)
pathlib
pathlib.Path.mkdirnow has a parent_mode parameter that allows specifying the mode for intermediate directories whenparents=True. (Contributed by Gregory P. Smith in86533.)
pdb
- Use the new interactive shell as the default input shell for
pdb. (Contributed by Tian Gao in145379.)
pickle
- Add support for pickling private methods and nested classes. (Contributed by Zackery Spytz and Serhiy Storchaka in
77188.)
pickletools
- The output of the
pickletoolscommand-line interface is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in149026.)
pprint
- Add an expand keyword argument for
pprint.pprint,pprint.pformat,pprint.pp. If true, the output will be formatted similar to pretty-printedjson.dumpswhen indent is supplied. (Contributed by Stefan Todoran, Semyon Moroz and Hugo van Kemenade in112632.) - Add t-string support to
pprint. (Contributed by Loïc Simon and Hugo van Kemenade in134551.)
re
re.prefixmatchand a correspondingre.Pattern.prefixmatchhave been added as alternate, more explicit names for the existing and nowsoft deprecatedre.matchandre.Pattern.matchAPIs. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search. (Contributed by Gregory P. Smith in86519.)
resource
- Add new constants:
~resource.RLIMIT_NTHR,~resource.RLIMIT_UMTXP,~resource.RLIMIT_THREADS,~resource.RLIM_SAVED_CUR, and~resource.RLIM_SAVED_MAX. (Contributed by Serhiy Storchaka in137512.)
shelve
- Added new
!reorganizemethod toshelveused to recover unused free space previously occupied by deleted entries. (Contributed by Andrea Oliveri in134004.) - Add support for custom serialization and deserialization functions in the
shelvemodule. (Contributed by Furkan Onder in99631.)
shutil
shutil.copyfilenow also raises~shutil.SpecialFileErrorfor sockets and device files. (Contributed by Savannah Ostrowski in142693.)
socket
- Add constants for the ISO-TP CAN protocol. (Contributed by Patrick Menschel and Stefan Tatschner in
86819.)
sqlite3
-
The
command-line interface <sqlite3-cli>has several new features:- SQL keyword completion on
Tab. (Contributed by Long Tan in133393.)
- Prompts, error messages, and help text are now colored. This is enabled by default, see
using-on-controlling-colorfor details. (Contributed by Stan Ulbrych and Łukasz Langa in133461.) - Table, index, trigger, view, column, function, and schema completion on
Tab. (Contributed by Long Tan in136101.)
- SQL keyword completion on
ssl
-
Indicate through
ssl.HAS_PSK_TLS13whether thesslmodule supports "External PSKs" in TLSv1.3, as described in9258. (Contributed by Will Childs-Klein in133624.) -
Added new methods for managing groups used for SSL key agreement:
ssl.SSLContext.set_groupssets the groups allowed for doing key agreement, extending the previousssl.SSLContext.set_ecdh_curvemethod. This new API provides the ability to list multiple groups and supports fixed-field and post-quantum groups in addition to ECDH curves. This method can also be used to control what key shares are sent in the TLS handshake.ssl.SSLSocket.groupreturns the group selected for doing key agreement on the current connection after the TLS handshake completes. This call requires OpenSSL 3.2 or later.ssl.SSLContext.get_groupsreturns a list of all available key agreement groups compatible with the minimum and maximum TLS versions currently set in the context. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick in
136306.) -
Added a new method
ssl.SSLContext.set_ciphersuitesfor setting TLS 1.3 ciphers. For TLS 1.2 or earlier,ssl.SSLContext.set_ciphersshould continue to be used. Both calls can be made on the same context and the selected cipher suite will depend on the TLS version negotiated when a connection is made. (Contributed by Ron Frederick in137197.) -
Added new methods for managing signature algorithms:
ssl.get_sigalgsreturns a list of all available TLS signature algorithms. This call requires OpenSSL 3.4 or later.ssl.SSLContext.set_client_sigalgssets the signature algorithms allowed for certificate-based client authentication.ssl.SSLContext.set_server_sigalgssets the signature algorithms allowed for the server to complete the TLS handshake.ssl.SSLSocket.client_sigalgreturns the signature algorithm selected for client authentication on the current connection. This call requires OpenSSL 3.5 or later.ssl.SSLSocket.server_sigalgreturns the signature algorithm selected for the server to complete the TLS handshake on the current connection. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick in
138252.)
subprocess
-
subprocess.Popen.wait: whentimeoutis notNoneand the platform supports it, an efficient event-driven mechanism is used to wait for process termination:- Linux >= 5.3 uses
os.pidfd_open+select.poll. - macOS and other BSD variants use
select.kqueue+KQ_FILTER_PROC+KQ_NOTE_EXIT. - Windows keeps using
WaitForSingleObject(unchanged).
If none of these mechanisms are available, the function falls back to the traditional busy loop (non-blocking call and short sleeps). (Contributed by Giampaolo Rodola in
83069.) - Linux >= 5.3 uses
symtable
- Add
symtable.Function.get_cellsandsymtable.Symbol.is_cellmethods. (Contributed by Yashp002 in143504.)
sys
- Add
sys.abi_infonamespace to improve access to ABI information. (Contributed by Klaus Zimmermann in137476.)
sys.monitoring
- The
other events <monitoring-event-global>(PY_THROW,PY_UNWIND,RAISE,EXCEPTION_HANDLED, andRERAISE) can now be turned on and disabled on a per code object basis. Returning~sys.monitoring.DISABLEfrom a callback for one of these events disables the event for the entire code object (for the current tool), rather than raisingValueErroras in prior versions. (Contributed by Gabriele N. Tornetta in146182.)
tarfile
~tarfile.data_filternow normalizes symbolic link targets in order to avoid path traversal attacks. (Contributed by Petr Viktorin in127987and2025-4138.)~tarfile.TarFile.extractallnow skips fixing up directory attributes when a directory was removed or replaced by another kind of file. (Contributed by Petr Viktorin in127987and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallnow (re-)apply the extraction filter when substituting a link (hard or symbolic) with a copy of another archive member, and when fixing up directory attributes. The former raises a new exception,~tarfile.LinkFallbackError. (Contributed by Petr Viktorin for2025-4330and2024-12718.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallno longer extract rejected members when~tarfile.TarFile.errorlevelis zero. (Contributed by Matt Prodani and Petr Viktorin in112887and2025-4435.)~tarfile.TarFile.extractand~tarfile.TarFile.extractallnow replace slashes with backslashes in symlink targets on Windows to prevent creation of corrupted links. (Contributed by Christoph Walcher in57911.)~tarfile.TarFile.gettarinfonow replaces backslashes with slashes in symlink targets on Windows to conform to the tar format standard. (Contributed by Daniele Nicolodi in151669.)
threading
- Added
~threading.serialize_iterator,~threading.synchronized_iterator, and~threading.concurrent_teeto support concurrent access to generators and iterators. (Contributed by Raymond Hettinger in124397.)
timeit
- The output of the
timeitcommand-line interface is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in146609.) - The command-line interface now colorizes error tracebacks by default. This can be controlled with
environment variables <using-on-controlling-color>. (Contributed by Yi Hong in139374.) - Make the target time of
timeit.Timer.autorangeconfigurable and add--target-timeoption to the command-line interface. (Contributed by Alessandro Cucci and Miikka Koskinen in80642.)
tkinter
- The
!tkinter.Text.searchmethod now supports two additional arguments: nolinestop which allows the search to continue across line boundaries; and strictlimits which restricts the search to within the specified range. (Contributed by Rihaan Meher in130848.) - A new method
!tkinter.Text.search_allhas been introduced. This method allows for searching for all matches of a pattern using Tcl's-alland-overlapoptions. (Contributed by Rihaan Meher in130848.) - Added new methods
!pack_content,!place_contentand!grid_contentwhich use Tk commands with new names (introduced in Tk 8.6) instead of!*_slavesmethods which use Tk commands with outdated names. (Contributed by Serhiy Storchaka in143754.) - Added
!Eventattributes!user_datafor Tk virtual events and!detailforEnter,Leave,FocusIn,FocusOut, andConfigureRequestevents. (Contributed by Matthias Kievernagel and Serhiy Storchaka in47655.)
tokenize
- The output of the
tokenizecommand-line interface <tokenize-cli>is colored by default. This can be controlled withenvironment variables <using-on-controlling-color>. (Contributed by Hugo van Kemenade in148991.)
tomllib
-
The
tomllibmodule now supports TOML 1.1.0. This is a backwards compatible update, meaning that all valid TOML 1.0.0 documents are parsed the same way.The changes, according to the official TOML changelog, are:
-
Allow newlines and trailing commas in inline tables.
Previously an inline table had to be on a single line and couldn't end with a trailing comma. This is now relaxed so that the following is valid:
tbl = { key = "a string", moar-tbl = { key = 1, }, } -
Add
\xHHnotation to basic strings for codepoints under 255, and the\eescape for the escape character:null = "null byte: \x00; letter a: \x61" csi = "\e[" -
Seconds in datetime and time values are now optional. The following are now valid:
dt = 2010-02-03 14:15 t = 14:15
(Contributed by Taneli Hukkinen in
142956.) -
types
- Expose the write-through
localsproxy type astypes.FrameLocalsProxyType. This represents the type of theframe.f_localsattribute, as described in667. (Contributed by Peter Bierma in136492.)
typing
-
747: Add~typing.TypeForm, a new special form for annotating values that are themselves type expressions.TypeForm[T]means "a type form object describingT(or a type assignable toT)". At runtime,TypeForm(x)simply returnsx, which allows explicit annotation of type-form values without changing behavior.This helps libraries that accept user-provided type expressions (for example
int,str | None,~typing.TypedDictclasses, orlist[int]) expose precise signatures:from typing import Any, TypeForm def cast[T](typ: TypeForm[T], value: Any) -> T: ...(Contributed by Jelle Zijlstra in
145033.)
728: Add support in~typing.TypedDictfor the closed and extra_items class arguments. A closed~typing.TypedDictdoes not allow extra keys beyond those specified in the class body, while a~typing.TypedDictwithextra_itemsallows arbitrary extra items where the values are of the specified type. (Contributed by Angela Liss in137840.)- Code like
class ExtraTypeVars(P1[S], Protocol[T, T2]): ...now raises aTypeError, becauseSis not listed inProtocolparameters. (Contributed by Nikita Sobolev in137191.) - Code like
class B2(A[T2], Protocol[T1, T2]): ...now correctly handles type parameters order: it is(T1, T2), not(T2, T1)as it was incorrectly inferred at runtime before. (Contributed by Nikita Sobolev in137191.) 800: Addtyping.disjoint_base, a new decorator marking a class as a disjoint base. This is an advanced feature primarily intended to allow type checkers to faithfully reflect the runtime semantics of types defined as builtins or in compiled extensions. If a classCis a disjoint base, then child classes of that class cannot inherit from other disjoint bases that are not parent or child classes ofC. (Contributed by Jelle Zijlstra in148639.)~typing.TypeVarTuplenow acceptsbound,covariant,contravariant, andinfer_variancekeyword arguments, matching the interface of~typing.TypeVarand~typing.ParamSpec.boundsemantics remain undefined in the specification.
unicodedata
- The Unicode database has been updated to Unicode 17.0.0. (Contributed by Benjamin Peterson in
138706.) - Add
unicodedata.isxidstartandunicodedata.isxidcontinuefunctions to check whether a character can start or continue a Unicode Standard Annex #31 identifier. (Contributed by Stan Ulbrych in129117.) - Add the
~unicodedata.iter_graphemesfunction to iterate over grapheme clusters according to rules defined in Unicode Standard Annex #29, "Unicode Text Segmentation". Add~unicodedata.grapheme_cluster_break,~unicodedata.indic_conjunct_breakand~unicodedata.extended_pictographicfunctions to get the properties of the character which are related to the above algorithm. (Contributed by Serhiy Storchaka and Guillaume Sanchez in74902.) - Add
~unicodedata.blockfunction to return the Unicode block assigned to a character. (Contributed by Stan Ulbrych in66802.)
unittest
unittest.TestCase.assertLogswill now accept a formatter to control how messages are formatted. (Contributed by Garry Cairns in134567.)unittest.TestCase.assertWarnsandunittest.TestCase.assertWarnsRegexno longer swallow warnings that do not match the specified category or regex. Nested context managers are now supported. (Contributed by Serhiy Storchaka in143231.)
urllib.parse
- Add the missing_as_none parameter to
~urllib.parse.urlsplit,~urllib.parse.urlparseand~urllib.parse.urldefragfunctions. Add the keep_empty parameter to~urllib.parse.urlunsplitand~urllib.parse.urlunparsefunctions. This allows distinguishing between empty and undefined URI components and preserving empty components. (Contributed by Serhiy Storchaka in67041.)
venv
- On POSIX platforms, platlib directories will be created if needed when creating virtual environments, instead of using a
lib64 -> libsymlink. This means purelib and platlib of virtual environments no longer share the samelibdirectory on platforms wheresys.platlibdiris not equal tolib. (Contributed by Rui Xi in133951.)
warnings
- Improve filtering by module in
warnings.warn_explicitif no module argument is passed. It now tests the module regular expression in the warnings filter not only against the filename with.pystripped, but also against module names constructed starting from different parent directories of the filename (with/__init__.py,.pyand, on Windows,.pywstripped). (Contributed by Serhiy Storchaka in135801.)
wave
- Added support for IEEE floating-point WAVE audio (
WAVE_FORMAT_IEEE_FLOAT) inwave. - Added
wave.Wave_read.getformat,wave.Wave_write.getformat, andwave.Wave_write.setformatfor explicit frame format handling. wave.Wave_write.setparamsaccepts both 7-item tuples includingformatand 6-item tuples for backwards compatibility (defaulting toWAVE_FORMAT_PCM).WAVE_FORMAT_IEEE_FLOAToutput now includes afactchunk, as required for non-PCM WAVE formats.
(Contributed by Lionel Koenig and Michiel W. Beijen in 60729.)
webbrowser
- On macOS, the new
!webbrowser.MacOSclass opens URLs via/usr/bin/openinstead of constructing and executing AppleScript viaosascript. The default browser is detected from the LaunchServices preferences file usingplistlib, with!com.apple.Safarias the fallback on fresh installations. For non-HTTP(S) URLs,open -b <bundle-id>is used to route the URL through a browser rather than the OS file handler, preventing file injection attacks. (Contributed by Jeff Lyon in137586.)
xml
- Add the
xml.is_valid_namefunction to check whether a string can be used as an element or attribute name in XML. (Contributed by Serhiy Storchaka in139489.) - Add the
xml.is_valid_textfunction to check whether a string can be used in an XML document. (Contributed by Serhiy Storchaka in139489.)
xml.parsers.expat
- Add
~xml.parsers.expat.xmlparser.SetAllocTrackerActivationThresholdand~xml.parsers.expat.xmlparser.SetAllocTrackerMaximumAmplificationtoxmlparser <xmlparser-objects>objects to tune protections against disproportional amounts of dynamic memory usage from within an Expat parser. (Contributed by Bénédikt Tran in90949.) - Add
~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionActivationThresholdand~xml.parsers.expat.xmlparser.SetBillionLaughsAttackProtectionMaximumAmplificationtoxmlparser <xmlparser-objects>objects to tune protections against billion laughs attacks. (Contributed by Bénédikt Tran in90949.)
zlib
- Allow combining two Adler-32 checksums via
~zlib.adler32_combine. (Contributed by Callum Attryde and Bénédikt Tran in134635.) - Allow combining two CRC-32 checksums via
~zlib.crc32_combine. (Contributed by Bénédikt Tran in134635.)
Optimizations
mimallocis now used as the default allocator for raw memory allocations such as viaPyMem_RawMallocfor better performance onfree-threaded builds <free-threaded build>. (Contributed by Kumar Aditya in144914.)
base64 & binascii
- CPython's underlying base64 implementation now encodes 2x faster and decodes 3x faster thanks to simple CPU pipelining optimizations. (Contributed by Gregory P. Smith and Serhiy Storchaka in
143262.) - Implementation for Ascii85, Base85, and Z85 encoding has been rewritten in C. Encoding and decoding is now two orders of magnitude faster and consumes two orders of magnitude less memory. (Contributed by James Seo and Serhiy Storchaka in
101178.) - Implementation for Base32 has been rewritten in C. Encoding and decoding is now two orders of magnitude faster. (Contributed by James Seo in
146192.)
csv
csv.Sniffer.sniffdelimiter detection is now up to 1.6x faster. (Contributed by Maurycy Pawłowski-Wieroński in137628.)
Upgraded experimental JIT compiler
Results from the pyperformance benchmark suite report a 7-8% geometric mean performance improvement for the JIT over the standard CPython interpreter built with all optimizations enabled on x86-64 Linux. On AArch64 macOS, the JIT has an 11-12% speedup over the tail calling interpreter <whatsnew314-tail-call-interpreter> with all optimizations enabled. The speedups for JIT builds versus no JIT builds range from roughly 15% slowdown to over 100% speedup (ignoring the unpack_sequence microbenchmark) on x86-64 Linux and AArch64 macOS systems.
The major upgrades to the JIT are:
- LLVM 21 build-time dependency
- New tracing frontend
- Basic register allocation in the JIT
- More JIT optimizations
- GDB and GNU
backtrace()unwinding support - Better machine code generation
LLVM 21 build-time dependency
The JIT compiler now uses LLVM 21 for build-time stencil generation. As always, LLVM is only needed when building CPython with the JIT enabled; end users running Python do not need LLVM installed. Instructions for installing LLVM can be found in the JIT compiler documentation for all supported platforms. (Contributed by Savannah Ostrowski in 140973.)
A new tracing frontend
The JIT compiler now supports significantly more bytecode operations and control flow than in Python 3.14, enabling speedups on a wider variety of code. For example, simple Python object creation is now understood by the 3.15 JIT compiler. Overloaded operations and generators are also partially supported. This was made possible by an overhauled JIT tracing frontend that records actual execution paths through code, rather than estimating them as the previous implementation did. (Contributed by Ken Jin in 139109. Support for Windows added by Mark Shannon in 141703.)
Basic register allocation in the JIT
A basic form of register allocation has been added to the JIT compiler's optimizer. This allows the JIT compiler to avoid certain stack operations altogether and instead operate on registers. This allows the JIT to produce more efficient traces by avoiding reads and writes to memory. (Contributed by Mark Shannon in 135379.)
More JIT optimizations
More constant-propagation is now performed. This means when the JIT compiler detects that certain user code results in constants, the code can be simplified by the JIT. (Contributed by Ken Jin and Savannah Ostrowski in 132732.)
Reference counts <reference count> are avoided whenever it is safe to do so. This generally reduces the cost of most operations in Python. (Contributed by Ken Jin, Donghee Na, Zheao Li, Hai Zhu, Savannah Ostrowski, Reiden Ong, Noam Cohen, Tomas Roun, PuQing, Cajetan Rodrigues, and Sacul in 134584.)
By tracking unique references to objects, the JIT optimizer can now eliminate reference count updates and perform in-place operations on ints and floats. (Contributed by Reiden Ong, and Pieter Eendebak in 143414 and 146306.)
The JIT optimizer now supports significantly more operations than in 3.14. (Contributed by Kumar Aditya, Ken Jin, Jiahao Li, and Sacul in 131798.)
GDB and GNU backtrace() unwinding support
The JIT compiler now publishes unwind information for generated machine code to the GDB interface on supported Linux ELF platforms. When libgcc frame registration is available, the same unwind information is also registered for GNU backtrace() stack walkers. This allows native debuggers, crash handlers, and diagnostic tools using these mechanisms to unwind through JIT frames instead of stopping at generated code. (Contributed by Diego Russo and Pablo Galindo Salgado in 146071 and 149104.)
Better machine code generation
The JIT compiler's machine code generator now produces better machine code for x86-64 and AArch64 macOS and Linux targets. In general, users should experience lower memory usage for generated machine code and more efficient machine code versus 3.14. (Contributed by Brandt Bucher in 136528 and 135905. Implementation for AArch64 contributed by Mark Shannon in 139855. Additional optimizations for AArch64 contributed by Mark Shannon and Diego Russo in 140683 and 142305.)
Maintainability
The JIT optimizer's operations have been simplified. This was made possible by a refactoring of JIT data structures. (Contributed by Zhongtian Zheng in 148211 and Hai Zhu in 143421.)
Removed
ast
- The constructors of
AST nodes <ast_nodes>now raise aTypeErrorwhen a required argument is omitted or when a keyword argument that does not map to a field on the AST node is passed. These cases had previously raised aDeprecationWarningsince Python 3.13. (Contributed by Brian Schubert and Jelle Zijlstra in137600and105858.)
collections.abc
collections.abc.ByteStringhas been removed fromcollections.abc.__all__.!collections.abc.ByteStringhas been deprecated since Python 3.12, and is scheduled for removal in Python 3.17. (Contributed by Alex Waygood in118803.)
ctypes
- Removed the undocumented function
!ctypes.SetPointerType, which has been deprecated since Python 3.13. (Contributed by Bénédikt Tran in133866.)
datetime
~datetime.datetime.strptimenow raisesValueErrorwhen the format string contains%d(day of month) without a year directive. This has been deprecated since Python 3.13. (Contributed by Stan Ulbrych and Gregory P. Smith in70647.)
glob
- Removed the undocumented
!glob.glob0and!glob.glob1functions, which have been deprecated since Python 3.13. Useglob.globand pass a directory to its root_dir argument instead. (Contributed by Barney Gale in137466.)
http.server
- Removed the
!CGIHTTPRequestHandlerclass and the--cgiflag from thepython -m http.servercommand-line interface. They were deprecated in Python 3.13. (Contributed by Bénédikt Tran in133810.)
importlib
- The
load_module()methods of~importlib.abc.Loaderand its subclasses is removed. The import system will no longer call it when defined on custom subclasses. The method has been deprecated in favor of~importlib.abc.Loader.exec_modulesince Python 3.4. (Contributed by Brett Cannon in97850.)
importlib.resources
- Removed deprecated
packageparameter fromimportlib.resources.filesfunction. (Contributed by Semyon Moroz in138044.)
pathlib
- Removed deprecated
!pathlib.PurePath.is_reserved. Useos.path.isreservedto detect reserved paths on Windows. (Contributed by Nikita Sobolev in133875.)
platform
- Removed the
!platform.java_verfunction, which was deprecated since Python 3.13. (Contributed by Alexey Makridenko in133604.)
sre*
- Removed
!sre_compile,!sre_constantsand!sre_parsemodules. (Contributed by Stan Ulbrych in135994.)
sysconfig
- Removed the check_home parameter of
sysconfig.is_python_build. (Contributed by Filipe Laíns in92897.)
threading
- Remove support for arbitrary positional or keyword arguments in the C implementation of
~threading.RLockobjects. This was deprecated in Python 3.14. (Contributed by Bénédikt Tran in134087.)
types
- Removed
!codeobject.co_lnotabfromtypes.CodeType, deprecated since Python 3.12 by626. (Contributed by Nikita Sobolev in134690.)
typing
typing.ByteStringhas been removed fromtyping.__all__.!typing.ByteStringhas been deprecated since Python 3.9, and is scheduled for removal in Python 3.17. (Contributed by Alex Waygood in118803.)- The undocumented keyword argument syntax for creating
~typing.NamedTupleclasses (for example,Point = NamedTuple("Point", x=int, y=int)) is no longer supported. Use the class-based syntax or the functional syntax instead. (Contributed by Bénédikt Tran in133817.) - Using
TD = TypedDict("TD")orTD = TypedDict("TD", None)to construct a~typing.TypedDicttype with zero fields is no longer supported. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})instead. (Contributed by Bénédikt Tran in133823.) - Deprecated
!typing.no_type_check_decoratorhas been removed. (Contributed by Nikita Sobolev in133601.)
wave
- Removed the
getmark(),setmark()andgetmarkers()methods of the~wave.Wave_readand~wave.Wave_writeclasses, which were deprecated since Python 3.13. (Contributed by Bénédikt Tran in133873.)
zipimport
- Remove deprecated
!zipimport.zipimporter.load_module. Usezipimport.zipimporter.exec_moduleinstead. (Contributed by Jiahao Li in133656.)
Deprecated
New deprecations
ast:-
Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.(Contributed by Brian Schubert in
116021.)
-
base64:- Accepting the
+and/characters with an alternative alphabet in~base64.b64decodeand~base64.urlsafe_b64decodeis now deprecated. In future Python versions they will be errors in the strict mode and discarded in the non-strict mode. (Contributed by Serhiy Storchaka in125346.)
- Accepting the
- CLI:
-
Deprecate
-band!-bbcommand-line options and schedule them to become no-ops in Python 3.17. These were primarily helpers for the Python 2 -> 3 transition. Starting with Python 3.17, noBytesWarningwill be raised for these cases; use a type checker instead.(Contributed by Nikita Sobolev in
136355.)
-
collections.abc:-
The following statements now cause
DeprecationWarnings to be emitted at runtime:from collections.abc import ByteStringimport collections.abc; collections.abc.ByteString.
DeprecationWarnings were already emitted ifcollections.abc.ByteStringwas subclassed or used as the second argument toisinstanceorissubclass, but warnings were not previously emitted if it was merely imported or accessed from the!collections.abcmodule. (Contributed by Alex Waygood in118803.)
-
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, the optional initial data parameter could also be passed as a keyword argument nameddata=orstring=in varioushashlibimplementations.Support for the
stringkeyword argument name is now deprecated and is slated for removal in Python 3.19. Prefer passing the initial data as a positional argument for maximum backwards compatibility.(Contributed by Bénédikt Tran in
134978.)
-
http.cookies:Morsel.js_output <http.cookies.Morsel.js_output>andBaseCookie.js_output <http.cookies.BaseCookie.js_output>are deprecated and will be removed in Python 3.19. UseMorsel.output <http.cookies.Morsel.output>orBaseCookie.output <http.cookies.BaseCookie.output>instead. (Contributed by kishorhange111 in148849.)
imaplib:- Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not explicitly close the current file. (Contributed by Bénédikt Tran in142307.)
- Altering
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
re:-
re.matchandre.Pattern.matchare nowsoft deprecatedin favor of the newre.prefixmatchandre.Pattern.prefixmatchAPIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.We do not plan to remove the older
!matchname, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use!match, while new code should prefer!prefixmatch. Seeprefixmatch-vs-match.(Contributed by Gregory P. Smith in
86519and Hugo van Kemenade in148100.)
-
struct:-
Calling
Struct.__new__()without a required argument is now deprecated and will be removed in Python 3.20. Calling the~object.__init__method on an initialized~struct.Structobject is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
'F'and'D'type codes are nowsoft deprecatedin favor of the two-letter forms'Zf'and'Zd'. (Contributed by Sergey B Kirpichev in121249.)
-
typing:-
The following statements now cause
DeprecationWarnings to be emitted at runtime:from typing import ByteStringimport typing; typing.ByteString.
DeprecationWarnings were already emitted iftyping.ByteStringwas subclassed or used as the second argument toisinstanceorissubclass, but warnings were not previously emitted if it was merely imported or accessed from the!typingmodule. (Contributed by Alex Waygood in118803.) -
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOSand scheduled for removal in Python 3.17. (Contributed by Jeff Lyon in137586.)
__version__:-
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.)
-
Pending removal in Python 3.16
- The import system:
- Setting
~module.__loader__on a module while failing to set__spec__.loader <importlib.machinery.ModuleSpec.loader>is deprecated. In Python 3.16,!__loader__will cease to be set or taken into consideration by the import system or the standard library. - Setting
~module.__package__on a module while failing to set__spec__.parent <importlib.machinery.ModuleSpec.parent>is deprecated. In Python 3.16,!__package__will cease to be taken into consideration by the import system or standard library. (97879)
- Setting
- The bundled copy of
libmpdec. array:- The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
- The
asyncio:-
!asyncio.iscoroutinefunctionis deprecated and will be removed in Python 3.16; useinspect.iscoroutinefunctioninstead. (Contributed by Jiahao Li and Kumar Aditya in122875.) -
asynciopolicy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:!asyncio.AbstractEventLoopPolicy!asyncio.DefaultEventLoopPolicy!asyncio.WindowsSelectorEventLoopPolicy!asyncio.WindowsProactorEventLoopPolicy!asyncio.get_event_loop_policy!asyncio.set_event_loop_policy
Users should use
asyncio.runorasyncio.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)(Contributed by Kumar Aditya in
127949.)
-
builtins:- 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:- Calling the Python implementation of
functools.reducewith function or sequence as keyword arguments has been deprecated since Python 3.14.
- Calling the Python implementation of
logging:- 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.)
- 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:- Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type. Undotted extensions are deprecated and will raise aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in75223.)
- Valid extensions start with a '.' or are empty for
shutil:- The
!ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4, and is now an alias ofRuntimeError.
- The
symtable:- The
!symtable.Class.get_methodsmethod has been deprecated since Python 3.14.
- The
sys:- The
!_enablelegacywindowsfsencodingfunction has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
- The
sysconfig:- The
!sysconfig.expand_makefile_varsfunction has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead.
- The
tarfile:- The undocumented and unused
!TarInfo.tarfileattribute has been deprecated since Python 3.13.
- The undocumented and unused
Pending removal in Python 3.17
datetime:~datetime.datetime.strptimecalls using a format string containing%e(day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in70647.)
collections.abc:-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements thebuffer protocol <bufferobjects>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
encodings:- Passing non-ascii encoding names to
encodings.normalize_encodingis deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in136702.)
- Passing non-ascii encoding names to
profile:- The
!profilemodule is deprecated and will be removed in Python 3.17. Useprofiling.tracinginstead, which provides a compatible API. See799for details. (Contributed by Pablo Galindo and László Kiss Kollár in138122.)
- The
webbrowser:!webbrowser.MacOSXOSAScriptis deprecated in favour of!webbrowser.MacOS. (137586)
typing:-
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_originandtyping.get_argsinstead of relying on private implementation details. -
typing.ByteString, 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>at runtime. For use in type annotations, either use~collections.abc.Bufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).!ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance of!ByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere also never understood as subtypes of!ByteString(either at runtime or by static type checkers).See
PEP 688 <688#current-options>for more details. (Contributed by Shantanu Jain in91896.)
-
tkinter:- The
!tkinter.Variablemethods!trace_variable,!trace(an alias of!trace_variable),!trace_vdeleteand!trace_vinfo, deprecated since Python 3.14, are scheduled for removal in Python 3.17. Use!trace_add,!trace_removeand!trace_infoinstead. (Contributed by Serhiy Storchaka in120220.)
- The
Pending removal in Python 3.18
-
No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in
82626.) -
decimal:- The non-standard and undocumented
~decimal.Decimalformat specifier'N', which is only supported in the!decimalmodule's C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in89902.)
- The non-standard and undocumented
-
Deprecations defined by
829:importlines in{name}.pthfiles are silently ignored.
(Contributed by Barry Warsaw in
148641.)
Pending removal in Python 3.19
builtins:- Passing a complex number as the real or imag argument in the
complexconstructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in109218.)
- Passing a complex number as the real or imag argument in the
ctypes:- Implicitly switching to the MSVC-compatible struct layout by setting
~ctypes.Structure._pack_but not~ctypes.Structure._layout_on non-Windows platforms.
- Implicitly switching to the MSVC-compatible struct layout by setting
hashlib:-
In hash function constructors such as
~hashlib.newor the direct hash-named constructors such as~hashlib.md5and~hashlib.sha256, their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in various!hashlibimplementations.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.
-
http.cookies:http.cookies.Morsel.js_outputis deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_outputis deprecated and will be removed in Python 3.19.
imaplib:-
Altering
IMAP4.file <imaplib.IMAP4.file>is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.Before Python 3.14, this property was used to implement the corresponding
read()andreadline()methods for~imaplib.IMAP4but this is no longer the case since then.
-
tkinter:tkinter.filedialog.askopenfileshas been deprecated since Python 3.16. Iterate over the names returned by~tkinter.filedialog.askopenfilenamesand open them one by one instead. (Contributed by Serhiy Storchaka in152638.)
Pending removal in Python 3.20
-
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling~object.__init__method on initialized~struct.Structobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in
143715.) -
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.argparsecsvctypes!ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)http.serverimaplibipaddressjsonlogging(__date__also deprecated)optparsepickleplatformresocketservertabnannytarfiletkinter.fonttkinter.ttkwsgiref.simple_serverxml.etree.ElementTree!xml.sax.expatreaderxml.sax.handlerzlib
(Contributed by Hugo van Kemenade and Stan Ulbrych in
76007.) -
The
__author__,__credits__,__copyright__and__date__attributes have been deprecated in these standard library modules and will be removed in Python 3.20. Attribution is preserved in the source code and the version control history.bz2concurrent.futuresinspectiojsonloggingoptparseplatformpydoctarfiletkinter.ttktokenizeuuid
(Contributed by Stan Ulbrych in
159240.) -
Deprecations defined by
829:- Warnings are produced for
importlines found in{name}.pthfiles. {name}.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in
148641.) - Warnings are produced for
-
ast:- Creating instances of abstract AST nodes (such as
ast.ASTor!ast.expr) is deprecated and will raise an error in Python 3.20.
- Creating instances of abstract AST nodes (such as
-
typing:-
It is deprecated to call
isinstanceandissubclasschecks on protocol classes that were not explicitly decorated with!runtime_checkablebut that inherit from a runtime-checkable protocol class. This will raise aTypeErrorin Python 3.20.(Contributed by Bartosz Sławecki in
132604.)
-
Pending removal in Python 3.21
-
abc- Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively.
- Soft-deprecated since Python 3.3
-
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
- Classes
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodis deprecated since Python 3.16 and will raiseTypeErrorin Python 3.21. Annotate the dispatch parameter or pass the dispatch type explicitly instead. (Contributed by Bartosz Sławecki in143465.)
- Using a return annotation to infer the dispatch type for
-
struct:- Soft-deprecated since Python 3.15, using
'F'and'D'type codes are now deprecated. These codes will be removed in Python 3.21. Use instead two-letter forms'Zf'and'Zd'.
- Soft-deprecated since Python 3.15, using
-
tempfile:tempfile._TemporaryFileWrapperwill be removed in Python 3.21. Use the publictempfile.TemporaryFileWrapperinstead.
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:- Nesting argument groups and nesting mutually exclusive groups are deprecated.
- Passing the undocumented keyword argument prefix_chars to
~argparse.ArgumentParser.add_argument_groupis now deprecated. - The
argparse.FileTypetype converter is deprecated.
builtins:- 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,else,for,if,in,isandor. In a future release it will be changed to a syntax error. (87999) - Support for
__index__()and__int__()method returning non-int type: these methods will be required to return an instance of a strict subclass ofint. - Support for
__float__()method returning a strict subclass offloat: these methods will be required to return an instance offloat. - Support for
__complex__()method returning a strict subclass ofcomplex: these methods will be required to return an instance ofcomplex.
- Generators:
calendar:calendar.Januaryandcalendar.Februaryconstants are deprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY. (Contributed by Prince Roshan in103636.)codecs: useopeninstead ofcodecs.open. (133038)!codeobject.co_lnotab: use thecodeobject.co_linesmethod instead.datetime:~datetime.datetime.utcnow: usedatetime.datetime.now(tz=datetime.UTC).~datetime.datetime.utcfromtimestamp: usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: Plural value must be an integer.importlib:~importlib.util.cache_from_sourcedebug_override parameter is deprecated: use the optimization parameter instead.
importlib.metadata:EntryPointstuple interface.- Implicit
Noneon return values.
logging: thewarn()method has been deprecated since Python 3.3, use~logging.warninginstead.mailbox: Use of StringIO input and text mode is deprecated, use BytesIO and binary mode instead.os: Callingos.register_at_forkin a multi-threaded process.os.path:os.path.commonprefixis deprecated, useos.path.commonpathfor path prefixes. Theos.path.commonprefixfunction 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: A tuple value for exc_info parameter is deprecated, use an exception instance.re: 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.)shutil:~shutil.rmtree's onerror parameter is deprecated in Python 3.12; use the onexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:~ssl.SSLContext.set_npn_protocolsand!selected_npn_protocolare 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
threadingmethods:!threading.Condition.notifyAll: use~threading.Condition.notify_all.!threading.Event.isSet: use~threading.Event.is_set.!threading.Thread.isDaemon,threading.Thread.setDaemon: usethreading.Thread.daemonattribute.!threading.Thread.getName,threading.Thread.setName: usethreading.Thread.nameattribute.!threading.currentThread: usethreading.current_thread.!threading.activeCount: usethreading.active_count.
typing.Text(92332).- The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. 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.) unittest.IsolatedAsyncioTestCase: it is deprecated to return a value that is notNonefrom a test case.urllib.parsedeprecated functions:~urllib.parse.urlparseinsteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partial writes.xml.etree.ElementTree: Testing the truth value of an~xml.etree.ElementTree.Elementis deprecated. In a future release it will always returnTrue. Prefer explicitlen(elem)orelem is not Nonetests instead.sys._clear_type_cacheis deprecated: usesys._clear_internal_cachesinstead.
Soft deprecations
There are no plans to remove soft deprecated APIs.
-
re.matchandre.Pattern.matchare nowsoft deprecatedin favor of the newre.prefixmatchandre.Pattern.prefixmatchAPIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python's "Explicit is better than implicit" mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.We do not plan to remove the older
!matchname, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use!match, while new code should prefer!prefixmatch. Seeprefixmatch-vs-match.(Contributed by Gregory P. Smith in
86519and Hugo van Kemenade in148100.)
C API changes
New features
-
Add
PyArg_ParseArrayandPyArg_ParseArrayAndKeywordsfunctions to parse arguments of functions using theMETH_FASTCALLcalling convention. (Contributed by Victor Stinner in144175.) -
Add the following functions for the new
frozendicttype:PyAnyDict_CheckPyAnyDict_CheckExactPyFrozenDict_CheckPyFrozenDict_CheckExactPyFrozenDict_New
(Contributed by Victor Stinner in
141510.) -
Add
PyObject_CallFinalizerFromDeallocfunction to the limited C API. (Contributed by Victor Stinner in146063.) -
Add
PySys_GetAttr,PySys_GetAttrString,PySys_GetOptionalAttr, andPySys_GetOptionalAttrStringfunctions as replacements forPySys_GetObject. (Contributed by Serhiy Storchaka in108512.) -
Add
PyUnstable_Unicode_GET_CACHED_HASHto get the cached hash of a string. See the documentation for caveats. (Contributed by Petr Viktorin in131510.) -
Add API for checking an extension module's ABI compatibility:
Py_mod_abi,PyABIInfo_Check, andPyABIInfo_VAR. (Contributed by Petr Viktorin in137210.)
-
Implement
782, thePyBytesWriter API <pybyteswriter>. Add functions:PyBytesWriter_CreatePyBytesWriter_DiscardPyBytesWriter_FinishPyBytesWriter_FinishWithPointerPyBytesWriter_FinishWithSizePyBytesWriter_FormatPyBytesWriter_GetDataPyBytesWriter_GetSizePyBytesWriter_GrowPyBytesWriter_GrowAndUpdatePointerPyBytesWriter_ResizePyBytesWriter_WriteBytes
(Contributed by Victor Stinner in
129813.) -
PyCriticalSectionand related functions are added to the Stable ABI. (Contributed by Petr Viktorin in149225.) -
Add a new
PyImport_CreateModuleFromInitfuncC API for creating a module from a spec and initfunc. (Contributed by Itamar Oren in116146.) -
Add
PyTuple_FromArrayto create atuplefrom an array. (Contributed by Victor Stinner in111489.) -
Add a new module export hook,
PyModExport_* <PyModExport_modulename>.(Contributed by Petr Viktorin in
793and140550.) -
Add functions that are guaranteed to be safe for use in
~PyTypeObject.tp_traversehandlers:PyObject_GetTypeData_DuringGC,PyObject_GetItemData_DuringGC,PyType_GetModuleState_DuringGC,PyModule_GetState_DuringGC,PyModule_GetToken_DuringGC,PyType_GetBaseByToken_DuringGC,PyType_GetModule_DuringGC,PyType_GetModuleByToken_DuringGC. (Contributed by Petr Viktorin in145925.) -
Add
PyObject_Dumpto dump an object tostderr. It should only be used for debugging. (Contributed by Victor Stinner in141070.) -
Implement
820:PySlot-- Unified slot system for the C API. Seecapi-slotsfor documentation.This adds:
- The
PySlotstruct; - the
PyType_FromSlotsfunction; - new slot IDs:
Py_slot_end,Py_slot_invalid;Py_slot_subslots,Py_tp_slots,Py_mod_slots;Py_tp_name,Py_tp_basicsize,Py_tp_extra_basicsize,Py_tp_itemsize,Py_tp_flags,Py_tp_metaclass,Py_tp_module; - convenience macros:
PySlot_DATA,PySlot_FUNC,PySlot_SIZE,PySlot_INT64,PySlot_UINT64,PySlot_STATIC_DATA,PySlot_END,PySlot_PTR,PySlot_PTR_STATIC.
The
PyModule_FromSlotsAndSpecfunction andPyModExportmodule export hook <extension-export-hook>also use the new!PySlotstruct.The following functions are
soft deprecated:PyType_FromSpecPyType_FromSpecWithBasesPyType_FromModuleAndSpecPyType_FromMetaclassPyModule_FromDefAndSpecPyModule_FromDefAndSpec2PyModule_ExecDef
The slots
Py_tp_basesandPy_tp_baseare now equivalent: they can be set either to a single type or a tuple of types. ThePy_tp_basesslot is preferred; the other is ignored if both are specified.(Contributed by Petr Viktorin in
149044.) - The
-
Add
PyUnstable_ThreadState_SetStackProtectionandPyUnstable_ThreadState_ResetStackProtectionfunctions to set the stack protection base address and stack protection size of a Python thread state. (Contributed by Victor Stinner in139653.) -
Add
PyUnstable_SetImmortalC API function to mark objects asimmortal. (Contributed by Kumar Aditya in143300.) -
Restore private provisional
_Py_InitializeMain()function removed in Python 3.14. (Contributed by Victor Stinner in142417.) -
Add
PyUnstable_DumpTracebackandPyUnstable_DumpTracebackThreadsfunctions to output Python stacktraces. (Contributed by Alex Malyshev in145559.)
Changed C APIs
- If the
Py_TPFLAGS_MANAGED_DICTorPy_TPFLAGS_MANAGED_WEAKREFflag is set thenPy_TPFLAGS_HAVE_GCmust be set too. (Contributed by Sergey Miryanov in134786.) PyDateTime_IMPORTis now thread safe. Code that directly checksPyDateTimeAPIforNULLshould be updated to callPyDateTime_IMPORTinstead. (Contributed by Kumar Aditya in141563.)
Removed C APIs
-
Remove deprecated
PyUnicodefunctions:!PyUnicode_AsDecodedObject: UsePyCodec_Decodeinstead.!PyUnicode_AsDecodedUnicode: UsePyCodec_Decodeinstead; note that some codecs (for example, "base64") may return a type other thanstr, such asbytes.!PyUnicode_AsEncodedObject: UsePyCodec_Encodeinstead.!PyUnicode_AsEncodedUnicode: UsePyCodec_Encodeinstead; note that some codecs (for example, "base64") may return a type other thanbytes, such asstr.
(Contributed by Stan Ulbrych in
133612.) -
!PyImport_ImportModuleNoBlock: deprecated alias ofPyImport_ImportModule. (Contributed by Bénédikt Tran in133644.) -
!PyWeakref_GetObjectand!PyWeakref_GET_OBJECT: usePyWeakref_GetRefinstead. The [|pythoncapi_compat_project_link|](https://github.com/python/pythoncapi-compat) can be used to get!PyWeakref_GetRefon Python 3.12 and older. (Contributed by Bénédikt Tran in133644.) -
Remove deprecated
!PySys_ResetWarnOptions. Clearsys.warnoptionsand!warnings.filtersinstead.(Contributed by Nikita Sobolev in
138886.)
The following functions are removed in favor of PyConfig_Get. The [|pythoncapi_compat_project_link|](https://github.com/python/pythoncapi-compat) can be used to get !PyConfig_Get on Python 3.13 and older.
-
Python initialization functions:
!Py_GetExecPrefix: usePyConfig_Get("base_exec_prefix") <PyConfig_Get>(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix") <PyConfig_Get>(sys.exec_prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetPath: usePyConfig_Get("module_search_paths") <PyConfig_Get>(sys.path) instead.!Py_GetPrefix: usePyConfig_Get("base_prefix") <PyConfig_Get>(sys.base_prefix) instead. UsePyConfig_Get("prefix") <PyConfig_Get>(sys.prefix) ifvirtual environments <venv-def>need to be handled.!Py_GetProgramFullPath: usePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetProgramName: usePyConfig_Get("executable") <PyConfig_Get>(sys.executable) instead.!Py_GetPythonHome: usePyConfig_Get("home") <PyConfig_Get>or thePYTHONHOMEenvironment variable instead.
(Contributed by Bénédikt Tran in
133644.)
Deprecated C APIs
-
Deprecate
456support for providing an external definition of the string hashing scheme. Removal is scheduled for Python 3.19.Previously, embedders could define
Py_HASH_ALGORITHMto bePy_HASH_EXTERNALto indicate that the hashing scheme was provided externally but this feature was undocumented, untested and most likely unused.(Contributed by Bénédikt Tran in
141226.) -
For unsigned integer formats in
PyArg_ParseTuple, accepting Python integers with value that is larger than the maximal value for the C type or less than the minimal value for the corresponding signed integer type of the same size is now deprecated. (Contributed by Serhiy Storchaka in132629.) -
PyBytes_FromStringAndSize(NULL, len) <PyBytes_FromStringAndSize>and_PyBytes_Resizearesoft deprecated, use thePyBytesWriterAPI instead. (Contributed by Victor Stinner in129813.) -
!_PyObject_CallMethodId,!_PyObject_GetAttrIdand!_PyUnicode_FromIdare deprecated since Python 3.15 and will be removed in Python 3.20. Instead, usePyUnicode_InternFromString()and cache the result in the module state, then callPyObject_CallMethodorPyObject_GetAttr. (Contributed by Victor Stinner in141049.) -
Deprecate
~PyComplexObject.cvalfield of thePyComplexObjecttype. UsePyComplex_AsCComplexandPyComplex_FromCComplexto convert a Python complex number to/from the CPy_complexrepresentation. (Contributed by Sergey B Kirpichev in128813.) -
Functions
_Py_c_sum,_Py_c_diff,_Py_c_neg,_Py_c_prod,_Py_c_quot,_Py_c_powand_Py_c_absaresoft deprecated. (Contributed by Sergey B Kirpichev in128813.) -
~PyConfig.bytes_warningis deprecated since Python 3.15 and will be removed in Python 3.17. (Contributed by Nikita Sobolev in136355.) -
!Py_INFINITYmacro issoft deprecated, use the C11 standard<math.h>!INFINITYinstead. (Contributed by Sergey B Kirpichev in141004.) -
The following macros are
soft deprecated:Py_ALIGNED: Preferalignasinstead.PY_FORMAT_SIZE_T: Use"z"directly.Py_LLandPy_ULL: Use standard suffixes,LLandULL.PY_LONG_LONG,PY_LLONG_MIN,PY_LLONG_MAX,PY_ULLONG_MAX,PY_INT32_T,PY_UINT32_T,PY_INT64_T,PY_UINT64_T,PY_SIZE_MAX: Use C99 types/limits.Py_UNICODE_SIZE: Usesizeof(wchar_t)directly.Py_VA_COPY: Useva_copydirectly.
The macro
Py_UNICODE_WIDE, which was scheduled for removal, issoft deprecatedinstead.(Contributed by Petr Viktorin in
146175.) -
!Py_MATH_Eland!Py_MATH_PIlare deprecated since Python 3.15 and will be removed in Python 3.20. (Contributed by Sergey B Kirpichev in141004.)
Build changes
-
Removed implicit fallback to the bundled copy of the
libmpdeclibrary. Now this should be explicitly enabled with!--with-system-libmpdecset tonoor with!--without-system-libmpdec. (Contributed by Sergey B Kirpichev in115119.) -
The new configure option
--with-missing-stdlib-config=FILEallows distributors to pass a JSON configuration file containing custom error messages forstandard librarymodules that are missing or packaged separately. (Contributed by Stan Ulbrych and Petr Viktorin in139707.) -
The new configure option
--with-pymalloc-hugepagesenables huge page support forpymalloc <pymalloc>arenas. When enabled, arena size increases to 2 MiB and allocation usesMAP_HUGETLB(Linux) orMEM_LARGE_PAGES(Windows) with automatic fallback to regular pages. On Windows, usebuild.bat --pymalloc-hugepages. At runtime, huge pages must be explicitly enabled by setting thePYTHON_PYMALLOC_HUGEPAGESenvironment variable to1. (Contributed by Pablo Galindo Salgado in144319.) -
Annotating anonymous mmap usage is now supported if the Linux kernel supports
PR_SET_VMA_ANON_NAME <PR_SET_VMA(2const)>(Linux 5.17 or newer). Annotations are visible in/proc/<pid>/mapsif the kernel supports the feature and-X dev <-X>is passed to Python, or Python is built indebug mode <debug-build>. (Contributed by Donghee Na in141770.) -
CPython is now built with frame pointers enabled by default (
831). Pass--without-frame-pointersto opt out.Authors of C extensions and native libraries built with custom build systems should ensure the unwind chain is intact. This is usually done by adding
-fno-omit-frame-pointerand similar flags toCFLAGS. See--without-frame-pointersdocumentation for the specific flags Python uses.(Contributed by Pablo Galindo Salgado and Savannah Ostrowski in
149201.)
- 64-bit builds using Visual Studio 2026 (MSVC 18) may now use the new
tail-calling interpreter <whatsnew314-tail-call-interpreter>. Results on Visual Studio 18.1.1 report between 15-20% speedup on the geometric mean of pyperformance on Windows x86-64 over the switch-case interpreter on an AMD Ryzen 7 5800X. We have observed speedups ranging from 14% for large pure-Python libraries to 40% for long-running small pure-Python scripts on Windows. This was made possible by a new feature introduced in MSVC 18, which the official Windows 64-bit binaries on python.org now use. (Contributed by Chris Eibl, Ken Jin, and Brandt Bucher in143068. Special thanks to Steve Dower, and the MSVC team including Hulon Jenkins.)
Porting to Python 3.15
This section lists previously described changes and other bugfixes that may require changes to your code.
-
sqlite3.ConnectionAPIs have been cleaned up.- All parameters of
sqlite3.connectexcept database are now keyword-only. - The first three parameters of methods
~sqlite3.Connection.create_functionand~sqlite3.Connection.create_aggregateare now positional-only. - The first parameter of methods
~sqlite3.Connection.set_authorizer,~sqlite3.Connection.set_progress_handlerand~sqlite3.Connection.set_trace_callbackis now positional-only.
(Contributed by Serhiy Storchaka in
133595.) - All parameters of
-
resource.RLIM_INFINITYis now always positive. Passing a negative integer value that corresponded to its old value (such as-1or-3, depending on platform) toresource.setrlimitandresource.prlimitis now deprecated. (Contributed by Serhiy Storchaka in137044.) -
mmap.mmap.resizehas been removed on platforms that don't support the underlying syscall, instead of raising aSystemError. (Contributed by An Long in138205.) -
A resource warning is now emitted for an unclosed
xml.etree.ElementTree.iterparseiterator if it opened a file. Use its!closemethod or thecontextlib.closingcontext manager to close it. (Contributed by Osama Abdelkader and Serhiy Storchaka in140601.) -
If a short option and a single-dash long option are passed to
argparse.ArgumentParser.add_argument, dest is now inferred from the single-dash long option. For example, inadd_argument('-f', '-foo'), dest is now'foo'instead of'f'. Pass an explicit dest argument to preserve the old behavior. (Contributed by Serhiy Storchaka in138697.) -
Padding of input no longer required in
base64.urlsafe_b64decode. Pass a new argumentpadded=Trueor usebase64.b64decodewith argumentaltchars=b'-_'(this works with older Python versions) to make padding required. (Contributed by Serhiy Storchaka in73613.) -
Since
unittest.TestCase.assertWarnsandunittest.TestCase.assertWarnsRegexno longer swallow warnings that do not match the specified category or regex, your tests may start leaking some warnings that were previously masked. Use warning filters to silence them or additional!assertWarns*to catch and check them. (Contributed by Serhiy Storchaka in143231.)
谢谢你的反馈!