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:

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

Tachyon profiler logo

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 applications

    • Run and profile scripts directly (run) - profile from the very start of execution

    • Execute 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 inAttributeErrorexceptions 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 noencoding argument 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 withthePYTHONUTF8=0 environment variable or the-Xutf8=0 command-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 whendelattr() 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__() ofImportError andModuleNotFoundErrornow 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-W option and thePYTHONWARNINGS environment 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 asDecimal andFraction),not only integers or floats, although this does not improve precision.(Contributed by Serhiy Storchaka ingh-67795.)

  • Addedbytearray.take_bytes(n=None,/) to takebytes out of abytearray without copying. This enables optimizing codewhich must returnbytes after 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

    Returnbytes after working withbytearray

    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 ascompile(),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

  • TheBooleanOptionalAction action supports now single-dashlong options and alternate prefix characters.(Contributed by Serhiy Storchaka ingh-138525.)

  • Changed thesuggest_on_error parameter ofargparse.ArgumentParser todefault 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 thecalendar.HTMLCalendar class now supportdark mode and have been migrated to the HTML5 standard for improved accessibility.(Contributed by Jiahao Li and Hugo van Kemenade ingh-137634.)

  • Thecalendar’scommand-line HTML output nowaccepts the year-month option:python-mcalendar-thtml200906.(Contributed by Pål Grønås Drange ingh-140212.)

collections

  • Addedcollections.Counter.__xor__() andcollections.Counter.__ixor__() to compute the symmetric differencebetweenCounter objects.(Contributed by Raymond Hettinger ingh-138682.)

collections.abc

  • collections.abc.ByteString has been removed fromcollections.abc.__all__.collections.abc.ByteString has beendeprecated since Python 3.12, and is scheduled for removal in Python 3.17.

  • The following statements now causeDeprecationWarnings to be emitted atruntime:

    • fromcollections.abcimportByteString

    • importcollections.abc;collections.abc.ByteString.

    DeprecationWarnings were already emitted ifcollections.abc.ByteString was subclassed or used as the secondargument toisinstance() orissubclass(), but warnings were notpreviously emitted if it was merely imported or accessed from thecollections.abc module.

concurrent.futures

  • Improved error reporting when a child process in aconcurrent.futures.ProcessPoolExecutor terminates 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 newreorganize() methods todbm.dumb anddbm.sqlite3which allow to recover unused free space previously occupied by deleted entries.(Contributed by Andrea Oliveri ingh-134004.)

difflib

functools

hashlib

  • Ensure that hash functions guaranteed to be alwaysavailable exist asattributes ofhashlib even if they will not work at runtime due tomissing backend implementations. For instance,hashlib.md5 will nolonger raiseAttributeError if 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 toHTTPConnection andHTTPSConnectionconstructors. 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

  • Add parametersinherit_class_doc andfallback_to_class_docforgetdoc().(Contributed by Serhiy Storchaka ingh-132686.)

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

mimetypes

  • Addapplication/node MIME type for.cjs extension. (Contributed by John Franey ingh-140937.)

  • Addapplication/toml. (Contributed by Gil Forcada ingh-139959.)

  • Renameapplication/x-texinfo toapplication/texinfo.(Contributed by Charlie Lin ingh-140165.)

  • Changed the MIME type for.ai files toapplication/pdf.(Contributed by Stan Ulbrych ingh-141239.)

mmap

  • mmap.mmap now has atrackfd parameter on Windows;if it isFalse, the file handle corresponding tofileno willnot be duplicated.(Contributed by Serhiy Storchaka ingh-78502.)

os

  • Addos.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

resource

shelve

  • Added newreorganize() method toshelve used to recover unused freespace previously occupied by deleted entries.(Contributed by Andrea Oliveri ingh-134004.)

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 throughssl.HAS_PSK_TLS13 whether thessl modulesupports “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 methodssl.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:

    (Contributed by Ron Frederick ingh-138252.)

sys

  • Addsys.abi_info namespace to improve access to ABI information.(Contributed by Klaus Zimmermann ingh-137476.)

tarfile

timeit

  • The command-line interface now colorizes error tracebacksby default. This can be controlled withenvironment variables.(Contributed by Yi Hong ingh-139374.)

tkinter

  • Thetkinter.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 methodtkinter.Text.search_all() has been introduced.This method allows for searching for all matches of a patternusing Tcl’s-all and-overlap options.(Contributed by Rihaan Meher ingh-130848)

types

unicodedata

unittest

venv

  • On POSIX platforms, platlib directories will be created if needed whencreating virtual environments, instead of usinglib64->lib symlink.This means purelib and platlib of virtual environments no longer share thesamelib directory on platforms wheresys.platlibdir is notequal tolib.(Contributed by Rui Xi ingh-133951.)

warnings

  • Improve filtering by module inwarnings.warn_explicit() if nomoduleargument is passed.It now tests the module regular expression in the warnings filter not onlyagainst the filename with.py stripped, but also against module namesconstructed starting from different parent directories of the filename(with/__init__.py,.py and, on Windows,.pyw stripped).(Contributed by Serhiy Storchaka ingh-135801.)

xml.parsers.expat

zlib

Optimizations

csv

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 functionctypes.SetPointerType(),which has been deprecated since Python 3.13.(Contributed by Bénédikt Tran ingh-133866.)

glob

  • Removed the undocumentedglob.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 theCGIHTTPRequestHandler classand the--cgi flag from thepython -m http.servercommand-line interface. They were deprecated in Python 3.13.(Contributed by Bénédikt Tran ingh-133810.)

importlib.resources

pathlib

  • Removed deprecatedpathlib.PurePath.is_reserved().Useos.path.isreserved() to detect reserved paths on Windows.(Contributed by Nikita Sobolev ingh-133875.)

platform

  • Removed theplatform.java_ver() function,which was deprecated since Python 3.13.(Contributed by Alexey Makridenko ingh-133604.)

sre_*

  • Removedsre_compile,sre_constants andsre_parse modules.(Contributed by Stan Ulbrych ingh-135994.)

sysconfig

threading

  • Remove support for arbitrary positional or keyword arguments in the Cimplementation ofRLock objects. This was deprecatedin Python 3.14.(Contributed by Bénédikt Tran ingh-134087.)

typing

  • The undocumented keyword argument syntax for creatingNamedTuple classes (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.)

  • UsingTD=TypedDict("TD") orTD=TypedDict("TD",None) toconstruct aTypedDict type with zero fields is nolonger supported. UseclassTD(TypedDict):passorTD=TypedDict("TD",{}) instead.(Contributed by Bénédikt Tran ingh-133823.)

  • Code likeclassExtraTypeVars(P1[S],Protocol[T,T2]):... now raisesaTypeError, becauseS is not listed inProtocol parameters.(Contributed by Nikita Sobolev ingh-137191.)

  • Code likeclassB2(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.ByteString has been removed fromtyping.__all__.typing.ByteString has been deprecated since Python 3.9, and isscheduled for removal in Python 3.17.

  • The following statements now causeDeprecationWarnings to be emitted atruntime:

    • fromtypingimportByteString

    • importtyping;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 thetyping module.

  • Deprecatedtyping.no_type_check_decorator() has been removed.(Contributed by Nikita Sobolev ingh-133601.)

wave

  • Removed thegetmark(),setmark() andgetmarkers() methodsof theWave_read andWave_write classes,which were deprecated since Python 3.13.(Contributed by Bénédikt Tran ingh-133873.)

zipimport

Deprecated

New deprecations

Pending removal in Python 3.16

Pending removal in Python 3.17

  • collections.abc:

    • collections.abc.ByteString is scheduled for removal in Python 3.17.

      Useisinstance(obj,collections.abc.Buffer) to test ifobjimplements thebuffer protocol at runtime. For usein type annotations, either useBuffer or a unionthat explicitly specifies the types your code supports (e.g.,bytes|bytearray|memoryview).

      ByteString was originally intended to be an abstract class thatwould serve as a supertype of bothbytes andbytearray.However, since the ABC never had any methods, knowing that an object was aninstance ofByteString never 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.)

  • encodings:

  • typing:

    • Before Python 3.14, old-style unions were implemented using the private classtyping._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.

      Useisinstance(obj,collections.abc.Buffer) to test ifobjimplements thebuffer protocol at runtime. For usein type annotations, either useBuffer or a unionthat explicitly specifies the types your code supports (e.g.,bytes|bytearray|memoryview).

      ByteString was originally intended to be an abstract class thatwould serve as a supertype of bothbytes andbytearray.However, since the ABC never had any methods, knowing that an object was aninstance ofByteString never 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

  • ctypes:

    • Implicitly switching to the MSVC-compatible struct layout by setting_pack_ but not_layout_on non-Windows platforms.

  • hashlib:

    • In hash function constructors such asnew() or thedirect hash-named constructors such asmd5() andsha256(), their optional initial data parameter couldalso be passed a keyword argument nameddata= orstring= invarioushashlib implementations.

      Support for thestring keyword argument name is now deprecatedand slated for removal in Python 3.19.

      Before Python 3.13, thestring keyword 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

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 exclusivegroups are deprecated.

    • Passing the undocumented keyword argumentprefix_chars toadd_argument_group() is nowdeprecated.

    • Theargparse.FileType type 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 example0inx,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,is andor. 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 ofint() to__trunc__() method.

    • Passing a complex number as thereal orimag argument in thecomplex() constructor is now deprecated; it should only be passedas a single positional argument.(Contributed by Serhiy Storchaka ingh-109218.)

  • calendar:calendar.January andcalendar.February constants aredeprecated and replaced bycalendar.JANUARY andcalendar.FEBRUARY.(Contributed by Prince Roshan ingh-103636.)

  • codecs: useopen() instead ofcodecs.open(). (gh-133038)

  • codeobject.co_lnotab: use thecodeobject.co_lines() methodinstead.

  • datetime:

    • utcnow():usedatetime.datetime.now(tz=datetime.UTC).

    • utcfromtimestamp():usedatetime.datetime.fromtimestamp(timestamp,tz=datetime.UTC).

  • gettext: Plural value must be an integer.

  • importlib:

    • cache_from_source()debug_override parameter isdeprecated: use theoptimization parameter instead.

  • importlib.metadata:

    • EntryPoints tuple interface.

    • ImplicitNone on 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.

  • ssl options and protocols:

    • ssl.SSLContext without protocol argument is deprecated.

    • ssl.SSLContext:set_npn_protocols() andselected_npn_protocol() are deprecated: use ALPNinstead.

    • ssl.OP_NO_SSL* options

    • ssl.OP_NO_TLS* options

    • ssl.PROTOCOL_SSLv3

    • ssl.PROTOCOL_TLS

    • ssl.PROTOCOL_TLSv1

    • ssl.PROTOCOL_TLSv1_1

    • ssl.PROTOCOL_TLSv1_2

    • ssl.TLSVersion.SSLv3

    • ssl.TLSVersion.TLSv1

    • ssl.TLSVersion.TLSv1_1

  • threading methods:

  • typing.Text (gh-92332).

  • The internal classtyping._UnionGenericAlias is 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 notNone from a test case.

  • urllib.parse deprecated functions:urlparse() instead

    • splitattr()

    • 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 anElement is deprecated. In a future release itwill always returnTrue. Prefer explicitlen(elem) orelemisnotNone tests instead.

  • sys._clear_type_cache() is deprecated:usesys._clear_internal_caches() instead.

C API changes

New features

Changed C APIs

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

The following functions are removed in favor ofPyConfig_Get().Thepythoncapi-compat project can be used to getPyConfig_Get()on Python 3.13 and older.

Deprecated C APIs

Build changes

  • Removed implicit fallback to the bundled copy of thelibmpdec library.Now this should be explicitly enabled with--with-system-libmpdecset tono or with--without-system-libmpdec.(Contributed by Sergey B Kirpichev ingh-115119.)

  • The new configure option--with-missing-stdlib-config=FILE allowsdistributors 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>/maps if the kernel supports the featureand-Xdev is 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.