What’s new in Python 3.15¶
- Editor:
Hugo van Kemenade
This article explains the new features in Python 3.15, compared to 3.14.
For full details, see thechangelog.
Note
Prerelease users should be aware that this document is currently in draftform. It will be updated substantially as Python 3.15 moves towards release,so it’s worth checking back even after reading earlier versions.
Summary – Release highlights¶
New features¶
PEP 799: A dedicated profiling package¶
A newprofiling module has been added to organize Python’s built-inprofiling 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).
ThecProfile module remains as an alias for backwards compatibility.Theprofile module is deprecated and will be removed in Python 3.17.
See also
PEP 799 for further details.
(Contributed by Pablo Galindo and László Kiss Kollár ingh-138122.)
Tachyon: High frequency statistical sampling profiler¶

A new statistical sampling profiler (Tachyon) has been added asprofiling.sampling. This profiler enables low-overhead performance analysis ofrunning Python processes without requiring code modification or process restart.
Unlike deterministic profilers (such asprofiling.tracing) that instrumentevery function call, the sampling profiler periodically captures stack traces fromrunning processes. This approach provides virtually zero overhead while achievingsampling rates ofup to 1,000,000 Hz, making it the fastest sampling profileravailable for Python (at the time of its contribution) and ideal for debuggingperformance issues in production environments. This capability is particularlyvaluable for debugging performance issues in production systems where traditionalprofiling approaches would be too intrusive.
Key features include:
Zero-overhead profiling: Attach to any running Python process withoutaffecting its performance. Ideal for production debugging where you can’t affordto 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 applicationsRun and profile scripts directly (
run) - profile from the very start of executionExecute and profile modules (
run-m) - profile packages run aspython-mmodule
Multiple profiling modes: Choose what to measure based on your performance investigation:
Wall-clock time (
--modewall, default): Measures real elapsed time including I/O,network waits, and blocking operations. Use this to understand where your program spendscalendar time, including when waiting for external resources.CPU time (
--modecpu): Measures only active CPU execution time, excluding I/O waitsand blocking. Use this to identify CPU-bound bottlenecks and optimize computational work.GIL-holding time (
--modegil): Measures time spent holding Python’s Global InterpreterLock. Use this to identify which threads dominate GIL usage in multi-threaded applications.Exception handling time (
--modeexception): Captures samples only from threads withan active exception. Use this to analyze exception handling overhead.
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-leveltiming with direct and cumulative samples. Best for detailed analysis and integration withexisting Python profiling tools.--collapsed: Generates collapsed stack traces (one line per stack). This format isspecifically designed for creating flamegraphs with external tools like Brendan Gregg’sFlameGraph scripts or speedscope.--flamegraph: Generates a self-contained interactive HTML flamegraph using D3.js.Opens directly in your browser for immediate visual analysis. Flamegraphs show the callhierarchy where width represents time spent, making it easy to spot bottlenecks at a glance.--gecko: Generates Gecko Profiler format compatible with Firefox Profiler(https://profiler.firefox.com). Upload the output to Firefox Profiler for advancedtimeline-based analysis with features like stack charts, markers, and network activity.--heatmap: Generates an interactive HTML heatmap visualization with line-level samplecounts. Creates a directory with per-file heatmaps showing exactly where time is spentat 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 onlyrunning tasks or all tasks including those waiting.Opcode-level profiling: Gather bytecode opcode information for instruction-levelprofiling (
--opcodes). Shows which bytecode instructions are executing, includingspecializations from the adaptive interpreter.
Seeprofiling.sampling for the complete documentation, including allavailable output formats, profiling modes, and configuration options.
(Contributed by Pablo Galindo and László Kiss Kollár ingh-135953 andgh-138122.)
Improved error messages¶
The interpreter now provides more helpful suggestions in
AttributeErrorexceptions when accessing an attribute on an object that does not exist, buta similar attribute is available through one of its members.For example, if the object has an attribute that itself exposes the requestedname, the error message will suggest accessing it via that inner attribute:
@dataclassclassCircle:radius:float@propertydefarea(self)->float:returnpi*self.radius**2classContainer:def__init__(self,inner:Circle)->None:self.inner=innercircle=Circle(radius=4.0)container=Container(circle)print(container.area)
Running this code now produces a clearer suggestion:
Traceback (most recent call last):File "/home/pablogsal/github/python/main/lel.py", line 42, in <module> print(container.area) ^^^^^^^^^^^^^^AttributeError:'Container' object has no attribute 'area'. Did you mean: 'inner.area'?
Other language changes¶
Python now usesUTF-8 as the default encoding, independent of the system’senvironment. 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-supportedUnicode character encoding that has become ade facto standard for representing text, including nearly every webpageon the internet, many common file formats, programming languages, and more.This only applies when no
encodingargument is given. For bestcompatibility between versions of Python, ensure that an explicitencodingargument is always provided. Theopt-in encoding warningcan be used to identify code that may be affected by this change.The specialencoding='locale'argument uses the current localeencoding, and has been supported since Python 3.10.To retain the previous behaviour, Python’s UTF-8 mode may be disabled withthe
PYTHONUTF8=0environment variable or the-Xutf8=0command-line option.See also
PEP 686 for further details.
(Contributed by Adam Turner ingh-133711; PEP 686 written by Inada Naoki.)
Several error messages incorrectly using the term “argument” have been corrected.(Contributed by Stan Ulbrych ingh-133382.)
The interpreter now tries to provide a suggestion when
delattr()fails 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:>>>classA:...pass>>>a=A()>>>a.abcde=1>>>dela.abcdfTraceback (most recent call last):...AttributeError:'A' object has no attribute 'abcdf'. Did you mean: 'abcde'?
(Contributed by Nikita Sobolev and Pranjal Prajapati ingh-136588.)
Unraisable exceptions are now highlighted with color by default. This can becontrolled byenvironment variables.(Contributed by Peter Bierma ingh-134170.)
The
__repr__()ofImportErrorandModuleNotFoundErrornow shows “name” and “path” asname=<name>andpath=<path>if they were givenas keyword arguments at construction time.(Contributed by Serhiy Storchaka, Oleg Iarygin, and Yoav Nir ingh-74185.)The
__dict__and__weakref__descriptors now use asingle descriptor instance per interpreter, shared across all types thatneed them.This speeds up class creation, and helps avoid reference cycles.(Contributed by Petr Viktorin ingh-135228.)The
-Woption and thePYTHONWARNINGSenvironment variablecan now specify regular expressions instead of literal strings to matchthe warning message and the module name, if the corresponding field startsand ends with a forward slash (/).(Contributed by Serhiy Storchaka ingh-134716.)Functions that take timestamp or timeout arguments now accept any realnumbers (such as
DecimalandFraction),not only integers or floats, although this does not improve precision.(Contributed by Serhiy Storchaka ingh-67795.)
Added
bytearray.take_bytes(n=None,/)to takebytes out of abytearraywithout copying. This enables optimizing codewhich must returnbytesafter working with a mutable buffer of bytessuch as data buffering, network protocol parsing, encoding, decoding,and compression. Common code patterns which can be optimized withtake_bytes()are listed below.Suggested optimizing refactors¶ Description
Old
New
defread()->bytes:buffer=bytearray(1024)...returnbytes(buffer)
defread()->bytes:buffer=bytearray(1024)...returnbuffer.take_bytes()
Empty a buffer getting the bytes
buffer=bytearray(1024)...data=bytes(buffer)buffer.clear()
buffer=bytearray(1024)...data=buffer.take_bytes()
Split a buffer at a specific separator
buffer=bytearray(b'abc\ndef')n=buffer.find(b'\n')data=bytes(buffer[:n+1])delbuffer[:n+1]assertdata==b'abc'assertbuffer==bytearray(b'def')
buffer=bytearray(b'abc\ndef')n=buffer.find(b'\n')data=buffer.take_bytes(n+1)
Split a buffer at a specific separator; discard after the separator
buffer=bytearray(b'abc\ndef')n=buffer.find(b'\n')data=bytes(buffer[:n])buffer.clear()assertdata==b'abc'assertlen(buffer)==0
buffer=bytearray(b'abc\ndef')n=buffer.find(b'\n')buffer.resize(n)data=buffer.take_bytes()
(Contributed by Cody Maloney ingh-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 modulename to be passed. It is needed to unambiguouslyfiltersyntax warnings by module name.(Contributed by Serhiy Storchaka ingh-135801.)Allowed defining the__dict__ and__weakref____slots__for any class.(Contributed by Serhiy Storchaka ingh-41779.)
New modules¶
math.integer¶
This module provides access to the mathematical functions for integerarguments (PEP 791).(Contributed by Serhiy Storchaka ingh-81313.)
Improved modules¶
argparse¶
The
BooleanOptionalActionaction supports now single-dashlong options and alternate prefix characters.(Contributed by Serhiy Storchaka ingh-138525.)Changed thesuggest_on_error parameter of
argparse.ArgumentParsertodefault toTrue. This enables suggestions for mistyped arguments by default.(Contributed by Jakob Schluse ingh-140450.)Added backtick markup support in description and epilog text to highlightinline code when color output is enabled.(Contributed by Savannah Ostrowski ingh-142390.)
calendar¶
Calendar pages generated by the
calendar.HTMLCalendarclass now supportdark mode and have been migrated to the HTML5 standard for improved accessibility.(Contributed by Jiahao Li and Hugo van Kemenade ingh-137634.)The
calendar’scommand-line HTML output nowaccepts the year-month option:python-mcalendar-thtml200906.(Contributed by Pål Grønås Drange ingh-140212.)
collections¶
collections.abc¶
collections.abc.ByteStringhas been removed fromcollections.abc.__all__.collections.abc.ByteStringhas beendeprecated since Python 3.12, and is scheduled for removal in Python 3.17.The following statements now cause
DeprecationWarnings to be emitted atruntime:fromcollections.abcimportByteStringimportcollections.abc;collections.abc.ByteString.
DeprecationWarnings were already emitted ifcollections.abc.ByteStringwas subclassed or used as the secondargument toisinstance()orissubclass(), but warnings were notpreviously emitted if it was merely imported or accessed from thecollections.abcmodule.
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 theterminated process.(Contributed by Jonathan Berg ingh-139486.)
dataclasses¶
Annotations for generated
__init__methods no longer include internaltype names.
dbm¶
Added new
reorganize()methods todbm.dumbanddbm.sqlite3which allow to recover unused free space previously occupied by deleted entries.(Contributed by Andrea Oliveri ingh-134004.)
difflib¶
Introduced the optionalcolor parameter to
difflib.unified_diff(),enabling color output similar togit diff.This can be controlled byenvironment variables.(Contributed by Douglas Thor ingh-133725.)Improved the styling of HTML diff pages generated by the
difflib.HtmlDiffclass, and migrated the output to the HTML5 standard.(Contributed by Jiahao Li ingh-134580.)
functools¶
singledispatchmethod()now supports non-descriptorcallables.(Contributed by Serhiy Storchaka ingh-140873.)
hashlib¶
Ensure that hash functions guaranteed to be alwaysavailable exist asattributes of
hashlibeven if they will not work at runtime due tomissing backend implementations. For instance,hashlib.md5will nolonger raiseAttributeErrorif OpenSSL is not available and Pythonhas been built without MD5 support.(Contributed by Bénédikt Tran ingh-136929.)
http.client¶
A newmax_response_headers keyword-only parameter has been added to
HTTPConnectionandHTTPSConnectionconstructors. This parameter overrides the default maximum number of allowedresponse headers.(Contributed by Alexander Enrique Urieles Nieto ingh-131724.)
http.cookies¶
Allow ‘
"’ double quotes in cookie values.(Contributed by Nick Burns and Senthil Kumaran ingh-92936.)
inspect¶
locale¶
setlocale()now supports language codes with@-modifiers.@-modifiers are no longer silently removed ingetlocale(),but included in the language code.(Contributed by Serhiy Storchaka ingh-137729.)
math¶
Add
math.isnormal()andmath.issubnormal()functions.(Contributed by Sergey B Kirpichev ingh-132908.)Add
math.fmax(),math.fmin()andmath.signbit()functions.(Contributed by Bénédikt Tran ingh-135853.)
mimetypes¶
Add
application/nodeMIME type for.cjsextension. (Contributed by John Franey ingh-140937.)Add
application/toml. (Contributed by Gil Forcada ingh-139959.)Rename
application/x-texinfotoapplication/texinfo.(Contributed by Charlie Lin ingh-140165.)Changed the MIME type for
.aifiles toapplication/pdf.(Contributed by Stan Ulbrych ingh-141239.)
mmap¶
os¶
Add
os.statx()on Linux kernel versions 4.11 and later withglibc versions 2.28 and later.(Contributed by Jeffrey Bosboom and Victor Stinner ingh-83714.)
os.path¶
Add support of the all-but-last mode in
realpath().(Contributed by Serhiy Storchaka ingh-71189.)Thestrict parameter to
os.path.realpath()accepts 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 forCVE 2025-4517.)
resource¶
Add new constants:
RLIMIT_NTHR,RLIMIT_UMTXP,RLIMIT_THREADS,RLIM_SAVED_CUR, andRLIM_SAVED_MAX.(Contributed by Serhiy Storchaka ingh-137512.)
shelve¶
socket¶
Add constants for the ISO-TP CAN protocol.(Contributed by Patrick Menschel and Stefan Tatschner ingh-86819.)
sqlite3¶
Thecommand-line interface has several new features:
SQL keyword completion on <tab>.(Contributed by Long Tan ingh-133393.)
Prompts, error messages, and help text are now colored.This is enabled by default, seeControlling color fordetails.(Contributed by Stan Ulbrych and Łukasz Langa ingh-133461.)
Table, index, trigger, view, column, function, and schema completion on <tab>.(Contributed by Long Tan ingh-136101.)
ssl¶
Indicate through
ssl.HAS_PSK_TLS13whether thesslmodulesupports “External PSKs” in TLSv1.3, as described in RFC 9258.(Contributed by Will Childs-Klein ingh-133624.)Added new methods for managing groups used for SSL key agreement
ssl.SSLContext.set_groups()sets the groups allowed for doingkey agreement, extending the previousssl.SSLContext.set_ecdh_curve()method.This new API provides the ability to list multiple groups andsupports fixed-field and post-quantum groups in addition to ECDHcurves. This method can also be used to control what key sharesare sent in the TLS handshake.ssl.SSLSocket.group()returns the group selected for doing keyagreement on the current connection after the TLS handshake completes.This call requires OpenSSL 3.2 or later.ssl.SSLContext.get_groups()returns a list of all available keyagreement groups compatible with the minimum and maximum TLS versionscurrently set in the context. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick ingh-136306.)
Added a new method
ssl.SSLContext.set_ciphersuites()for setting TLS 1.3ciphers. For TLS 1.2 or earlier,ssl.SSLContext.set_ciphers()shouldcontinue to be used. Both calls can be made on the same context and theselected cipher suite will depend on the TLS version negotiated when aconnection is made.(Contributed by Ron Frederick ingh-137197.)Added new methods for managing signature algorithms:
ssl.get_sigalgs()returns a list of all available TLS signaturealgorithms. This call requires OpenSSL 3.4 or later.ssl.SSLContext.set_client_sigalgs()sets the signature algorithmsallowed for certificate-based client authentication.ssl.SSLContext.set_server_sigalgs()sets the signature algorithmsallowed for the server to complete the TLS handshake.ssl.SSLSocket.client_sigalg()returns the signature algorithmselected for client authentication on the current connection. This callrequires OpenSSL 3.5 or later.ssl.SSLSocket.server_sigalg()returns the signature algorithmselected for the server to complete the TLS handshake on the currentconnection. This call requires OpenSSL 3.5 or later.
(Contributed by Ron Frederick ingh-138252.)
sys¶
Add
sys.abi_infonamespace to improve access to ABI information.(Contributed by Klaus Zimmermann ingh-137476.)
tarfile¶
data_filter()now normalizes symbolic link targets in order toavoid path traversal attacks.(Contributed by Petr Viktorin ingh-127987 andCVE 2025-4138.)extractall()now skips fixing up directory attributeswhen a directory was removed or replaced by another kind of file.(Contributed by Petr Viktorin ingh-127987 andCVE 2024-12718.)extract()andextractall()now (re-)apply the extraction filter when substituting a link (hard orsymbolic) with a copy of another archive member, and when fixing updirectory attributes.The former raises a new exception,LinkFallbackError.(Contributed by Petr Viktorin forCVE 2025-4330 andCVE 2024-12718.)extract()andextractall()no longer extract rejected members whenerrorlevel()is zero.(Contributed by Matt Prodani and Petr Viktorin ingh-112887andCVE 2025-4435.)extract()andextractall()now replace slashes by backslashes in symlink targets on Windows to preventcreation of corrupted links.(Contributed by Christoph Walcher ingh-57911.)
timeit¶
The command-line interface now colorizes error tracebacksby default. This can be controlled withenvironment variables.(Contributed by Yi Hong ingh-139374.)
tkinter¶
The
tkinter.Text.search()method now supports two additionalarguments:nolinestop which allows the search tocontinue across line boundaries;andstrictlimits which restricts the search to within the specified range.(Contributed by Rihaan Meher ingh-130848)A new method
tkinter.Text.search_all()has been introduced.This method allows for searching for all matches of a patternusing Tcl’s-alland-overlapoptions.(Contributed by Rihaan Meher ingh-130848)
types¶
Expose the write-through
locals()proxy typeastypes.FrameLocalsProxyType.This represents the type of theframe.f_localsattribute,as described inPEP 667.
unicodedata¶
The Unicode database has been updated to Unicode 17.0.0.
Add
unicodedata.isxidstart()andunicodedata.isxidcontinue()functions to check whether a character can start or continue aUnicode Standard Annex #31 identifier.(Contributed by Stan Ulbrych ingh-129117.)
unittest¶
unittest.TestCase.assertLogs()will now accept a formatterto control how messages are formatted.(Contributed by Garry Cairns ingh-134567.)
venv¶
On POSIX platforms, platlib directories will be created if needed whencreating virtual environments, instead of using
lib64->libsymlink.This means purelib and platlib of virtual environments no longer share thesamelibdirectory on platforms wheresys.platlibdiris notequal tolib.(Contributed by Rui Xi ingh-133951.)
warnings¶
Improve filtering by module in
warnings.warn_explicit()if nomoduleargument is passed.It now tests the module regular expression in the warnings filter not onlyagainst the filename with.pystripped, but also against module namesconstructed starting from different parent directories of the filename(with/__init__.py,.pyand, on Windows,.pywstripped).(Contributed by Serhiy Storchaka ingh-135801.)
xml.parsers.expat¶
Add
SetAllocTrackerActivationThreshold()andSetAllocTrackerMaximumAmplification()toxmlparser objects to tune protections againstdisproportional amounts of dynamic memory usage from within an Expat parser.(Contributed by Bénédikt Tran ingh-90949.)Add
SetBillionLaughsAttackProtectionActivationThreshold()andSetBillionLaughsAttackProtectionMaximumAmplification()toxmlparser objects to tune protections againstbillion laughs attacks.(Contributed by Bénédikt Tran ingh-90949.)
zlib¶
Allow combining two Adler-32 checksums via
adler32_combine().(Contributed by Callum Attryde and Bénédikt Tran ingh-134635.)Allow combining two CRC-32 checksums via
crc32_combine().(Contributed by Bénédikt Tran ingh-134635.)
Optimizations¶
csv¶
csv.Sniffer.sniff()delimiter detection is now up to 1.6x faster.(Contributed by Maurycy Pawłowski-Wieroński ingh-137628.)
Upgraded JIT compiler¶
Results from thepyperformancebenchmark suite report3-4%geometric mean performance improvement for the JIT over the standard CPythoninterpreter built with all optimizations enabled. The speedups for JITbuilds versus no JIT builds range from roughly 20% slowdown to over100% speedup (ignoring theunpack_sequence microbenchmark) onx86-64 Linux and AArch64 macOS systems.
Attention
These results are not yet final.
The major upgrades to the JIT are:
LLVM 21 build-time dependency
New tracing frontend
Basic register allocation in the JIT
More JIT optimizations
Better machine code generation
LLVM 21 build-time dependency
The JIT compiler now uses LLVM 21 for build-time stencil generation. Asalways, LLVM is only needed when building CPython with the JIT enabled;end users running Python do not need LLVM installed. Instructions forinstalling LLVM can be found in theJIT compiler documentationfor all supported platforms.
(Contributed by Savannah Ostrowski ingh-140973.)
A new tracing frontend
The JIT compiler now supports significantly more bytecode operations andcontrol flow than in Python 3.14, enabling speedups on a wider variety ofcode. For example, simple Python object creation is now understood by the3.15 JIT compiler. Overloaded operations and generators are also partiallysupported. This was made possible by an overhauled JIT tracing frontendthat records actual execution paths through code, rather than estimatingthem as the previous implementation did.
(Contributed by Ken Jin ingh-139109. Support for Windows added byMark Shannon ingh-141703.)
Basic register allocation in the JIT
A basic form of register allocation has been added to the JIT compiler’soptimizer. This allows the JIT compiler to avoid certain stack operationsaltogether and instead operate on registers. This allows the JIT to producemore efficient traces by avoiding reads and writes to memory.
(Contributed by Mark Shannon ingh-135379.)
More JIT optimizations
Moreconstant-propagationis now performed. This means when the JIT compiler detects that certain usercode results in constants, the code can be simplified by the JIT.
(Contributed by Ken Jin and Savannah Ostrowski ingh-132732.)
The JIT avoidsreference counts where possible. This generallyreduces the cost of most operations in Python.
(Contributed by Ken Jin, Donghee Na, Zheao Li, Savannah Ostrowski,Noam Cohen, Tomas Roun, PuQing ingh-134584.)
Better machine code generation
The JIT compiler’s machine code generator now produces better machine codefor x86-64 and AArch64 macOS and Linux targets. In general, users shouldexperience lower memory usage for generated machine code and more efficientmachine code versus the old JIT.
(Contributed by Brandt Bucher ingh-136528 andgh-136528.Implementation for AArch64 contributed by Mark Shannon ingh-139855.Additional optimizations for AArch64 contributed by Mark Shannon andDiego Russo ingh-140683 andgh-142305.)
Removed¶
ctypes¶
Removed the undocumented function
ctypes.SetPointerType(),which has been deprecated since Python 3.13.(Contributed by Bénédikt Tran ingh-133866.)
glob¶
Removed the undocumented
glob.glob0()andglob.glob1()functions, which have been deprecated since Python 3.13. Useglob.glob()and pass a directory to itsroot_dir argument instead.(Contributed by Barney Gale ingh-137466.)
http.server¶
Removed the
CGIHTTPRequestHandlerclassand the--cgiflag from thepython -m http.servercommand-line interface. They were deprecated in Python 3.13.(Contributed by Bénédikt Tran ingh-133810.)
importlib.resources¶
Removed deprecated
packageparameterfromimportlib.resources.files()function.(Contributed by Semyon Moroz ingh-138044)
pathlib¶
Removed deprecated
pathlib.PurePath.is_reserved().Useos.path.isreserved()to detect reserved paths on Windows.(Contributed by Nikita Sobolev ingh-133875.)
platform¶
Removed the
platform.java_ver()function,which was deprecated since Python 3.13.(Contributed by Alexey Makridenko ingh-133604.)
sre_*¶
Removed
sre_compile,sre_constantsandsre_parsemodules.(Contributed by Stan Ulbrych ingh-135994.)
sysconfig¶
Removed thecheck_home parameter of
sysconfig.is_python_build().(Contributed by Filipe Laíns ingh-92897.)
threading¶
typing¶
The undocumented keyword argument syntax for creating
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 ingh-133817.)Using
TD=TypedDict("TD")orTD=TypedDict("TD",None)toconstruct aTypedDicttype with zero fields is nolonger supported. UseclassTD(TypedDict):passorTD=TypedDict("TD",{})instead.(Contributed by Bénédikt Tran ingh-133823.)Code like
classExtraTypeVars(P1[S],Protocol[T,T2]):...now raisesaTypeError, becauseSis not listed inProtocolparameters.(Contributed by Nikita Sobolev ingh-137191.)Code like
classB2(A[T2],Protocol[T1,T2]):...now correctly handlestype parameters order: it is(T1,T2), not(T2,T1)as it was incorrectly inferred in runtime before.(Contributed by Nikita Sobolev ingh-137191.)typing.ByteStringhas been removed fromtyping.__all__.typing.ByteStringhas been deprecated since Python 3.9, and isscheduled for removal in Python 3.17.The following statements now cause
DeprecationWarnings to be emitted atruntime:fromtypingimportByteStringimporttyping;typing.ByteString.
DeprecationWarnings were already emitted iftyping.ByteStringwas subclassed or used as the second argument toisinstance()orissubclass(), but warnings were not previously emitted if it was merelyimported or accessed from thetypingmodule.Deprecated
typing.no_type_check_decorator()has been removed.(Contributed by Nikita Sobolev ingh-133601.)
wave¶
Removed the
getmark(),setmark()andgetmarkers()methodsof theWave_readandWave_writeclasses,which were deprecated since Python 3.13.(Contributed by Bénédikt Tran ingh-133873.)
zipimport¶
Remove deprecated
zipimport.zipimporter.load_module().Usezipimport.zipimporter.exec_module()instead.(Contributed by Jiahao Li ingh-133656.)
Deprecated¶
New deprecations¶
CLI:
Deprecate
-band-bbcommand-line optionsand 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 raisedfor these cases; use a type checker instead.(Contributed by Nikita Sobolev ingh-136355.)
In hash function constructors such as
new()or thedirect hash-named constructors such asmd5()andsha256(), the optional initial data parameter couldalso be passed as a keyword argument nameddata=orstring=invarioushashlibimplementations.Support for the
stringkeyword argument name is now deprecated andis slated for removal in Python 3.19. Prefer passing the initial data asa positional argument for maximum backwards compatibility.(Contributed by Bénédikt Tran ingh-134978.)
__version__The
__version__attribute has been deprecated in these standard librarymodules and will be removed in Python 3.20.Usesys.version_infoinstead.ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)logging(__date__also deprecated)
(Contributed by Hugo van Kemenade and Stan Ulbrych ingh-76007.)
Pending removal in Python 3.16¶
The import system:
Setting
__loader__on a module whilefailing to set__spec__.loaderis deprecated. In Python 3.16,__loader__will cease to be set ortaken into consideration by the import system or the standard library.
The
'u'format code (wchar_t)has been deprecated in documentation since Python 3.3and at runtime since Python 3.13.Use the'w'format code (Py_UCS4)for Unicode characters instead.
asyncio.iscoroutinefunction()is deprecatedand will be removed in Python 3.16;useinspect.iscoroutinefunction()instead.(Contributed by Jiahao Li and Kumar Aditya ingh-122875.)asynciopolicy system is deprecated and will be removed in Python 3.16.In particular, the following classes and functions are deprecated:Users should use
asyncio.run()orasyncio.Runnerwithloop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:importasyncioasyncdefmain():...asyncio.run(main(),loop_factory=asyncio.SelectorEventLoop)
(Contributed by Kumar Aditya ingh-127949.)
Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12,as it produces surprising and unintuitive results (-2and-1).Usenotxinstead for the logical negation of a Boolean.In the rare case that you need the bitwise inversion ofthe underlying integer, convert tointexplicitly (~int(x)).
Calling the Python implementation of
functools.reduce()withfunctionorsequence as keyword arguments has been deprecated since Python 3.14.
Support for custom logging handlers with thestrm argument is deprecatedand scheduled for removal in Python 3.16. Define handlers with thestreamargument instead. (Contributed by Mariusz Felisiak ingh-115032.)
Valid extensions start with a ‘.’ or are empty for
mimetypes.MimeTypes.add_type().Undotted extensions are deprecated and willraise aValueErrorin Python 3.16.(Contributed by Hugo van Kemenade ingh-75223.)
The
ExecErrorexceptionhas been deprecated since Python 3.14.It has not been used by any function inshutilsince Python 3.4,and is now an alias ofRuntimeError.
The
Class.get_methodsmethodhas been deprecated since Python 3.14.
sys:The
_enablelegacywindowsfsencoding()functionhas been deprecated since Python 3.13.Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
The
sysconfig.expand_makefile_vars()functionhas been deprecated since Python 3.14.Use thevarsargument ofsysconfig.get_paths()instead.
The undocumented and unused
TarFile.tarfileattributehas been deprecated since Python 3.13.
Pending removal in Python 3.17¶
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj,collections.abc.Buffer)to test ifobjimplements thebuffer protocol at runtime. For usein type annotations, either useBufferor a unionthat explicitly specifies the types your code supports (e.g.,bytes|bytearray|memoryview).ByteStringwas originally intended to be an abstract class thatwould serve as a supertype of bothbytesandbytearray.However, since the ABC never had any methods, knowing that an object was aninstance ofByteStringnever actually told you anything usefulabout the object. Other common buffer types such asmemoryviewwere also never understood as subtypes ofByteString(either atruntime or by static type checkers).SeePEP 688 for more details.(Contributed by Shantanu Jain ingh-91896.)
Passing non-asciiencoding names to
encodings.normalize_encoding()is deprecated and scheduled for removal in Python 3.17.(Contributed by Stan Ulbrych ingh-136702)
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 Python3.17. Users should use documented introspection helpers liketyping.get_origin()andtyping.get_args()instead of relying on private implementation details.typing.ByteString, deprecated since Python 3.9, is scheduled for removal inPython 3.17.Use
isinstance(obj,collections.abc.Buffer)to test ifobjimplements thebuffer protocol at runtime. For usein type annotations, either useBufferor a unionthat explicitly specifies the types your code supports (e.g.,bytes|bytearray|memoryview).ByteStringwas originally intended to be an abstract class thatwould serve as a supertype of bothbytesandbytearray.However, since the ABC never had any methods, knowing that an object was aninstance ofByteStringnever actually told you anything usefulabout the object. Other common buffer types such asmemoryviewwere also never understood as subtypes ofByteString(either atruntime or by static type checkers).SeePEP 688 for more details.(Contributed by Shantanu Jain ingh-91896.)
Pending removal in Python 3.19¶
In hash function constructors such as
new()or thedirect hash-named constructors such asmd5()andsha256(), their optional initial data parameter couldalso be passed a keyword argument nameddata=orstring=invarioushashlibimplementations.Support for the
stringkeyword argument name is now deprecatedand slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctlysupported depending on the backend implementation of hash functions.Prefer passing the initial data as a positional argument for maximumbackwards compatibility.
Pending removal in Python 3.20¶
The
__version__attribute has been deprecated in these standard librarymodules and will be removed in Python 3.20.Usesys.version_infoinstead.ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)logging(__date__also deprecated)
(Contributed by Hugo van Kemenade and Stan Ulbrych ingh-76007.)
Pending removal in future versions¶
The following APIs will be removed in the future,although there is currently no date scheduled for their removal.
Nesting argument groups and nesting mutually exclusivegroups are deprecated.
Passing the undocumented keyword argumentprefix_chars to
add_argument_group()is nowdeprecated.The
argparse.FileTypetype converter is deprecated.
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
0inx,1orx,0if1else2. It allows confusing andambiguous expressions like[0x1forxiny](which can be interpreted as[0x1forxiny]or[0x1forxiny]). A syntax warning is raisedif the numeric literal is immediately followed by one of keywordsand,else,for,if,in,isandor. In a future release itwill be changed to a syntax error. (gh-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.Delegation of
int()to__trunc__()method.Passing a complex number as thereal orimag argument in the
complex()constructor is now deprecated; it should only be passedas a single positional argument.(Contributed by Serhiy Storchaka ingh-109218.)
calendar:calendar.Januaryandcalendar.Februaryconstants aredeprecated and replaced bycalendar.JANUARYandcalendar.FEBRUARY.(Contributed by Prince Roshan ingh-103636.)codecs: useopen()instead ofcodecs.open(). (gh-133038)codeobject.co_lnotab: use thecodeobject.co_lines()methodinstead.utcnow():usedatetime.datetime.now(tz=datetime.UTC).utcfromtimestamp():usedatetime.datetime.fromtimestamp(timestamp,tz=datetime.UTC).
gettext: Plural value must be an integer.cache_from_source()debug_override parameter isdeprecated: use theoptimization parameter instead.
EntryPointstuple interface.Implicit
Noneon return values.
logging: thewarn()method has been deprecatedsince Python 3.3, usewarning()instead.mailbox: Use of StringIO input and text mode is deprecated, useBytesIO and binary mode instead.os: Callingos.register_at_fork()in a multi-threaded process.pydoc.ErrorDuringImport: A tuple value forexc_info parameter isdeprecated, use an exception instance.re: More strict rules are now applied for numerical group referencesand group names in regular expressions. Only sequence of ASCII digits is nowaccepted as a numerical reference. The group name in bytes patterns andreplacement strings can now only contain ASCII letters and digits andunderscore.(Contributed by Serhiy Storchaka ingh-91760.)shutil:rmtree()’sonerror parameter is deprecated inPython 3.12; use theonexc parameter instead.ssloptions and protocols:ssl.SSLContextwithout protocol argument is deprecated.ssl.SSLContext:set_npn_protocols()andselected_npn_protocol()are deprecated: use ALPNinstead.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(): usenotify_all().threading.Event.isSet(): useis_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().
The internal class
typing._UnionGenericAliasis no longer used to implementtyping.Union. To preserve compatibility with users using this privateclass, a compatibility shim will be provided until at least Python 3.17. (Contributed byJelle Zijlstra ingh-105499.)unittest.IsolatedAsyncioTestCase: it is deprecated to return a valuethat is notNonefrom a test case.urllib.parsedeprecated functions:urlparse()insteadsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()should not do partialwrites.xml.etree.ElementTree: Testing the truth value of anElementis deprecated. In a future release itwill always returnTrue. Prefer explicitlen(elem)orelemisnotNonetests instead.sys._clear_type_cache()is deprecated:usesys._clear_internal_caches()instead.
C API changes¶
New features¶
Add
PySys_GetAttr(),PySys_GetAttrString(),PySys_GetOptionalAttr(), andPySys_GetOptionalAttrString()functions as replacements forPySys_GetObject().(Contributed by Serhiy Storchaka ingh-108512.)Add
PyUnstable_Unicode_GET_CACHED_HASHto get the cached hash ofa string. See the documentation for caveats.(Contributed by Petr Viktorin ingh-131510.)Add API for checking an extension module’s ABI compatibility:
Py_mod_abi,PyABIInfo_Check(),PyABIInfo_VARandPy_mod_abi.(Contributed by Petr Viktorin ingh-137210.)
ImplementPEP 782, thePyBytesWriter API.Add functions:
(Contributed by Victor Stinner ingh-129813.)
Add a new
PyImport_CreateModuleFromInitfunc()C-API for creatinga module from aspec andinitfunc.(Contributed by Itamar Oren ingh-116146.)Add
PyTuple_FromArray()to create atuplefrom an array.(Contributed by Victor Stinner ingh-111489.)Add
PyUnstable_Object_Dump()to dump an object tostderr.It should only be used for debugging.(Contributed by Victor Stinner ingh-141070.)Add
PyUnstable_ThreadState_SetStackProtection()andPyUnstable_ThreadState_ResetStackProtection()functions to setthe stack protection base address and stack protection size of a Pythonthread state.(Contributed by Victor Stinner ingh-139653.)
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 ingh-134786)
Porting to Python 3.15¶
Private functions promoted to public C APIs:
Thepythoncapi-compat project can be used to get most of these newfunctions on Python 3.14 and older.
Removed C APIs¶
Remove deprecated
PyUnicodefunctions:PyUnicode_AsDecodedObject():UsePyCodec_Decode()instead.PyUnicode_AsDecodedUnicode():UsePyCodec_Decode()instead; Note that some codecs (for example, “base64”)may return a type other thanstr, such asbytes.PyUnicode_AsEncodedObject():UsePyCodec_Encode()instead.PyUnicode_AsEncodedUnicode():UsePyCodec_Encode()instead; Note that some codecs (for example, “base64”)may return a type other thanbytes, such asstr.
(Contributed by Stan Ulbrych ingh-133612.)
PyImport_ImportModuleNoBlock(): deprecated aliasofPyImport_ImportModule().(Contributed by Bénédikt Tran ingh-133644.)PyWeakref_GetObject()andPyWeakref_GET_OBJECT:usePyWeakref_GetRef()instead. Thepythoncapi-compat projectcan be used to getPyWeakref_GetRef()on Python 3.12 and older.(Contributed by Bénédikt Tran ingh-133644.)Remove deprecated
PySys_ResetWarnOptions().Clearsys.warnoptionsandwarnings.filtersinstead.(Contributed by Nikita Sobolev ingh-138886.)
The following functions are removed in favor ofPyConfig_Get().Thepythoncapi-compat project can be used to getPyConfig_Get()on Python 3.13 and older.
Python initialization functions:
Py_GetExecPrefix():usePyConfig_Get("base_exec_prefix")(sys.base_exec_prefix) instead.UsePyConfig_Get("exec_prefix")(sys.exec_prefix) ifvirtual environmentsneed to be handled.Py_GetPath():usePyConfig_Get("module_search_paths")(sys.path) instead.Py_GetPrefix():usePyConfig_Get("base_prefix")(sys.base_prefix) instead.UsePyConfig_Get("prefix")(sys.prefix) ifvirtual environmentsneed to be handled.Py_GetProgramFullPath():usePyConfig_Get("executable")(sys.executable) instead.Py_GetProgramName():usePyConfig_Get("executable")(sys.executable) instead.Py_GetPythonHome():usePyConfig_Get("home")or thePYTHONHOMEenvironment variable instead.
(Contributed by Bénédikt Tran ingh-133644.)
Deprecated C APIs¶
For unsigned integer formats in
PyArg_ParseTuple(),accepting Python integers with value that is larger than the maximal valuefor the C type or less than the minimal value for the correspondingsigned integer type of the same size is now deprecated.(Contributed by Serhiy Storchaka ingh-132629.)PyBytes_FromStringAndSize(NULL,len)and_PyBytes_Resize()aresoft deprecated,use thePyBytesWriterAPI instead.(Contributed by Victor Stinner ingh-129813.)_PyObject_CallMethodId(),_PyObject_GetAttrId()and_PyUnicode_FromId()are deprecated since 3.15 and will be removed in3.20. Instead, usePyUnicode_InternFromString()and cache the result inthe module state, then callPyObject_CallMethod()orPyObject_GetAttr().(Contributed by Victor Stinner ingh-141049.)Deprecate
cvalfield of thePyComplexObjecttype.UsePyComplex_AsCComplex()andPyComplex_FromCComplex()to convert a Python complex number to/from the CPy_complexrepresentation.(Contributed by Sergey B Kirpichev ingh-128813.)Functions
_Py_c_sum(),_Py_c_diff(),_Py_c_neg(),_Py_c_prod(),_Py_c_quot(),_Py_c_pow()and_Py_c_abs()aresoft deprecated.(Contributed by Sergey B Kirpichev ingh-128813.)bytes_warningis deprecatedsince 3.15 and will be removed in 3.17.(Contributed by Nikita Sobolev ingh-136355.)Py_INFINITYmacro issoft deprecated,use the C11 standard<math.h>INFINITYinstead.(Contributed by Sergey B Kirpichev ingh-141004.)Py_MATH_ElandPy_MATH_PIlare deprecatedsince 3.15 and will be removed in 3.20.(Contributed by Sergey B Kirpichev ingh-141004.)
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 ingh-115119.)The new configure option
--with-missing-stdlib-config=FILEallowsdistributors to pass aJSONconfiguration file containing custom error messages forstandard librarymodules that are missing or packaged separately.(Contributed by Stan Ulbrych and Petr Viktorin ingh-139707.)Annotating anonymous mmap usage is now supported if Linux kernel supportsPR_SET_VMA_ANON_NAME (Linux 5.17 or newer).Annotations are visible in
/proc/<pid>/mapsif the kernel supports the featureand-Xdevis passed to the Python or Python is built indebug mode.(Contributed by Donghee Na ingh-141770)
Porting to Python 3.15¶
This section lists previously described changes and other bugfixesthat may require changes to your code.
sqlite3.ConnectionAPIs have been cleaned up.All parameters of
sqlite3.connect()exceptdatabase are now keyword-only.The first three parameters of methods
create_function()andcreate_aggregate()are now positional-only.The first parameter of methods
set_authorizer(),set_progress_handler()andset_trace_callback()is now positional-only.
(Contributed by Serhiy Storchaka ingh-133595.)
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.setrlimit()andresource.prlimit()is now deprecated.(Contributed by Serhiy Storchaka ingh-137044.)resize()has been removed on platforms that don’t support theunderlying syscall, instead of raising aSystemError.A resource warning is now emitted for an unclosed
xml.etree.ElementTree.iterparse()iterator if it opened a file.Use itsclose()method or thecontextlib.closing()contextmanager to close it.(Contributed by Osama Abdelkader and Serhiy Storchaka ingh-140601.)If a short option and a single-dash long option are passed to
argparse.ArgumentParser.add_argument(),dest is now inferred fromthe single-dash long option. For example, inadd_argument('-f','-foo'),dest is now'foo'instead of'f'.Pass an explicitdest argument to preserve the old behavior.(Contributed by Serhiy Storchaka ingh-138697.)