What's new in Python 3.16
Editor
Savannah Ostrowski
* 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.16, compared to 3.15.
For full details, see the changelog <changelog>.
[!NOTE] Prerelease users should be aware that this document is currently in draft form. It will be updated substantially as Python 3.16 moves towards release, so it's worth checking back even after reading earlier versions.
Summary -- Release highlights
New features
Other language changes
- The
iterfunction now accepts the stop_exception parameter. The created iterator stops when the callable raises the specified exception. The second parameter is now named stop_value and can be passed by keyword.aiternow accepts the same stop_value and stop_exception parameters, calling an asynchronous callable and awaiting the result. (Contributed by Serhiy Storchaka in64862.) memoryview.castnow allows casting a multidimensional F-contiguous view to a one-dimensional view. (Contributed by Jaemin Park in91484.)memoryview.castnow accepts an order parameter. Withorder='F'it returns a zero-copy Fortran-contiguous (column-major) view of a flat buffer, which is useful for interfacing with column-major libraries. (Contributed by Serhiy Storchaka in78959.)Frame objects <frame-objects>now supportweak references <weakref>. This allows associating extra data with active frames, for example in debuggers, without keeping the frames (and everything they reference) alive indefinitely. (Contributed by Łukasz Langa in102960.)TypeErrormessages for some instance methods called with too many positional arguments now suggest checking whether the method definition is missing theselfparameter. (Contributed by Suren Nihalani in152315.)anextandaiterare now implemented in Python instead of C. The awaitable returned byanext(it, default)and the__anext__()of the iterator returned byaiter(callable, ...)are now plain coroutines, so introspection tools such asasyncio.print_call_graphcan see through them into the awaited code. (Contributed by Kumar Aditya in157361.)
Default interactive shell
- The
REPLnow displays error messages when editing commands cannot be performed, such as when tab completion finds no matches or a history search fails. (Contributed by Bartosz Sławecki in148228.)
New modules
- None yet.
Improved modules
argparse
~argparse.ArgumentGroupand~argparse.MutuallyExclusiveGroup, the types returned by~argparse.ArgumentParser.add_argument_groupand~argparse.ArgumentParser.add_mutually_exclusive_group, are now public. The_-prefixed names remain as aliases. (Contributed by Bernát Gábor in144812.)
asyncio
- Add the mode parameter to
asyncio.loop.create_unix_serverandasyncio.start_unix_serverto set the permissions of the Unix socket file created for path. (Contributed by Sam Bull in94984.) - Add eager_tasks parameter to
asyncio.runfunction andasyncio.Runnerclass constructor. (Contributed by Andrew Svetlov in128289.)
bdb
bdb.BdbQuitis now a subclass ofBaseException, instead ofException, to allow it to be used for cleanly exiting the debugger without being accidentally caught by user code. (Contributed by Tian Gao in149337.)
bz2
- Added constants
~bz2.bzlib_versionand~bz2.bzlib_version_infowhich provide information about the version of the bzip2 compression library in use. (Contributed by Serhiy Storchaka in117404.)
codecs
- On platforms that provide the C library's
iconv(3)function, every encoding known toiconvfor which Python has no built-in codec is now available (for examplecp1133). Prefixing an encoding name withiconv:forces theiconv-based codec even when a built-in codec of the same name exists. (Contributed by Serhiy Storchaka in152997.)
compression.zstd
- Added constants
~compression.zstd.ZSTD_VERSIONand~compression.zstd.ZSTD_VERSION_INFOwhich provide information about the version of the zstd library that was used for building the module.~compression.zstd.zstd_version_infois now a named tuple. (Contributed by Serhiy Storchaka in117404.)
concurrent.futures
- The iterator returned by
concurrent.futures.Executor.mapis no longer automatically closed if a function call raises an exception. Use the!closemethod to explicitly close the iterator. (Contributed by xzmeng and Serhiy Storchaka in108518.)
concurrent.interpreters
~concurrent.interpreters.Interpreterobjects now support thecontext managerprotocol. Exiting thewithblock calls~concurrent.interpreters.Interpreter.close. (Contributed by Peter Bierma in158370.)
csv
csv.Sniffer.sniffnow deduces the dialect by trial parsing instead of heuristics based on matching isolated fragments and on character frequencies, so the result is consistent with howcsv.readerwill parse the sample. It can now detect the escapechar parameter, accepts non-ASCII delimiters in the delimiters argument, no longer misdetects the delimiter when the sample contains delimiter characters inside quoted fields, and no longer takes quadratic time on quoted samples. The results may differ from those of earlier Python versions. (Contributed by Serhiy Storchaka in83273.)csv.Sniffer.sniffnow detects the lineterminator parameter by a majority vote among the line endings of the sample, instead of always returning'\r\n'. (Contributed by Serhiy Storchaka in75008.)
ctypes
- Add
ctypes.util.structfor generating~ctypes.Structuretypes from an annotation-based syntax, similar to how thedataclassesmodule is used. (Contributed by Peter Bierma in104533.) - Add
ctypes.util.wrap_dll_functionfor generating function pointers through a function signature. (Contributed by Peter Bierma in153903.) - Added constants
~ctypes.LIBFFI_VERSION,~ctypes.libffi_version,~ctypes.LIBFFI_VERSION_INFOand~ctypes.libffi_version_info, which provide information about the version of the libffi library in use. They are only available with libffi 3.5 or later. (Contributed by Serhiy Storchaka in157487.) - Objects with an
!_as_parameter_attribute are now implicitly converted when passed for a~ctypes.POINTERargument. (Contributed by Peter Bierma in71990.) Callback functions <ctypes-callback-functions>can now return~ctypes.Structureand~ctypes.Unioninstances by value. (Contributed by Russell Keith-Magee in49960.)
curses
- The
cursescharacter-cell window methods now accept a full character cell --- a spacing character optionally followed by combining characters --- in addition to a single integer or byte character. This affects~curses.window.addch,~curses.window.bkgd,~curses.window.bkgdset,~curses.window.border,~curses.window.box,~curses.window.echochar,~curses.window.hline,~curses.window.inschand~curses.window.vline. Also add the wide-character read methods~curses.window.get_wstrand~curses.window.in_wstr, the counterparts of~curses.window.getstrand~curses.window.instrthat return astrrather thanbytes, and the module functionscurses.erasewchar,curses.killwcharandcurses.wunctrl, the wide-character counterparts ofcurses.erasechar,curses.killcharandcurses.unctrl. On a narrow (non-ncursesw) build the character cell holds a single character without combining marks, representable as one byte in the window's encoding, and~curses.window.in_wstrreturns its decoded text. (Contributed by Serhiy Storchaka in151757.) - Add the
curses.complexchartype, representing a styled character cell (its text, attributes and color pair), and the window methods~curses.window.in_wchand~curses.window.getbkgrndthat return one --- the counterparts of~curses.window.inchand~curses.window.getbkgd. The character-cell methods, such as~curses.window.addchand~curses.window.border, now also accept a~curses.complexchar. These work whether or not Python was built against a wide-character-aware curses library; on a narrow build a cell holds a single character representable as one byte in the window's encoding (so only 8-bit locales are supported). (Contributed by Serhiy Storchaka in152233.) - Add the
curses.complexstrtype, an immutable run of styled cells (the string counterpart of~curses.complexchar), and the window method~curses.window.in_wchstrthat returns one. The string-cell methods~curses.window.addstr,~curses.window.addnstr,~curses.window.insstrand~curses.window.insnstrnow also accept a~curses.complexstr. Like~curses.complexchar, it works whether or not Python was built against a wide-character-aware curses library. (Contributed by Serhiy Storchaka in152233.) - The wide-character
cursesfunctions and methods~curses.window.get_wch,~curses.window.get_wstr,curses.unget_wch,curses.erasewchar,curses.killwcharandcurses.wunctrlnow also work when Python is not built against a wide-character-aware curses library, on an 8-bit locale, where each character is a single byte in the relevant encoding.curses.ungetchnow also accepts a one-character string, likecurses.unget_wch; on a wide-character build it can be any character (previously a multibyte character raisedOverflowError). (Contributed by Serhiy Storchaka in152470.) - Add support for multiple terminals to the
cursesmodule: the new functionscurses.newterm,curses.set_termandcurses.new_prescr, the correspondingscreen <curses-screen-objects>object, and thewindow.use() <curses.window.use>method. (Contributed by Serhiy Storchaka in90092.) - Add the
curseswindow methods~curses.window.attr_get,~curses.window.attr_set,~curses.window.attr_on,~curses.window.attr_offand~curses.window.color_set, which pass the color pair as a separate argument instead of packing it into the attribute value, and the correspondingWA_*attribute constants. (Contributed by Serhiy Storchaka in152219.) - Add the
curses.term_attrsfunction, which returns the supported video attributes asWA_* <curses-wa-constants>values, the counterpart ofcurses.termattrs. (Contributed by Serhiy Storchaka in152332.) - Add the
WACS_*constants to thecursesmodule, the counterparts of theACS_* <curses-acs-codes>line-drawing codes ascurses.complexcharcells. (Contributed by Serhiy Storchaka in155863.) - Add the
cursesfunctionscurses.alloc_pair,curses.find_pair,curses.free_pairandcurses.reset_color_pairsfor dynamic color-pair management, available when built against a wide-character ncurses with extended-color support. (Contributed by Serhiy Storchaka in151774.) - Add the
cursesfunctions~curses.scr_dump,~curses.scr_restore,~curses.scr_initand~curses.scr_set, which dump the whole screen to a file and restore it. (Contributed by Serhiy Storchaka in152260.) - Add the
curseswindow method~curses.window.dupwin, which returns a new window that is an independent duplicate of an existing one. (Contributed by Serhiy Storchaka in152258.) - Add the soft-label-key functions to the
cursesmodule, which manage a row of labels along the bottom line of the screen:~curses.slk_init,~curses.slk_set,~curses.slk_label,~curses.slk_refresh,~curses.slk_noutrefresh,~curses.slk_clear,~curses.slk_restore,~curses.slk_touch, the attribute functions~curses.slk_attron,~curses.slk_attroff,~curses.slk_attrset,~curses.slk_attr,~curses.slk_attr_on,~curses.slk_attr_off,~curses.slk_attr_set, and~curses.slk_color. (Contributed by Serhiy Storchaka in152263.) - Add the
curseskey-management functions~curses.define_key,~curses.key_definedand~curses.keyok, available when built against an ncurses withNCURSES_EXT_FUNCS. (Contributed by Serhiy Storchaka in152334.) - Add the
curses.has_mousefunction and thecurses.window.mouse_trafomethod, completing thecursesmouse interface. (Contributed by Serhiy Storchaka in152325.) - Add
cursesfunctions and window methods that report state which could previously only be set, such ascurses.window.is_keypad,curses.window.getparentandcurses.is_cbreak, available when built against an ncurses withNCURSES_EXT_FUNCS. (Contributed by Serhiy Storchaka in151776.) - Add
curses.nofilter, which undoes the effect ofcurses.filter. (Contributed by Serhiy Storchaka in151744.) curses.textpad.Textboxnow supports entering and reading back the full Unicode range, including combining characters, when curses is built with wide-character support. (Contributed by Serhiy Storchaka in133031.)
datetime
- Add the
%Nfformat code (where N is from 1 to 6) todatetime.datetime.strftime,datetime.time.strftime,datetime.date.strftime,datetime.datetime.strptimeanddatetime.time.strptime. (Contributed by Stan Ulbrych and Karoline Pauls in157290.) - Add
datetime.timezone.name, the name passed to the constructor, orNoneif no name was passed. (Contributed by Stan Ulbrych in131210.)
dbm.gnu
- Added constants
~dbm.gnu.GDBM_VERSION_INFO,~dbm.gnu.gdbm_version_infoand~dbm.gnu.gdbm_version, which provide information about the version of the GDBM library in use. (Contributed by Serhiy Storchaka in157478.)
dbm.ndbm
- Added constants which provide information about the version of the underlying library in use:
~dbm.ndbm.GDBM_VERSION_INFO,~dbm.ndbm.gdbm_version_infoand~dbm.ndbm.gdbm_versionif it is GDBM, or~dbm.ndbm.BDB_VERSION,~dbm.ndbm.bdb_version,~dbm.ndbm.BDB_VERSION_INFOand~dbm.ndbm.bdb_version_infoif it is Berkeley DB.dbm.ndbm.libraryis now'ndbm'instead of'GNU gdbm'for a classic NDBM library. (Contributed by Serhiy Storchaka in157480.)
decimal
- Added constants
~decimal.LIBMPDEC_VERSION,~decimal.libmpdec_version,~decimal.LIBMPDEC_VERSION_INFO, and~decimal.libmpdec_version_infoin the C implementation, which provide information about the version of the libmpdec library in use. (Contributed by Serhiy Storchaka in157475.)
difflib
- Expose the optional autojunk parameter of
difflib.SequenceMatcherin public functions and class methods indifflib, allowing callers to control the automatic junk heuristic. (Contributed by Tomasz Kazimierczak in118150.)
encodings
- Add the
utf-7-imapcodec, implementing the modified UTF-7 encoding used for international IMAP4 mailbox names (3501). (Contributed by Serhiy Storchaka in66788.) encodings.idna.nameprepnow takes a limit argument that allows rejecting extremely large input early. (Contributed by Petr Viktorin in157675.)
gzip
gzip.opennow accepts an optional argumentmtimewhich is passed on to the constructor of the~gzip.GzipFileclass. (Contributed by Marin Misur in91372.)
imaplib
- Add the
~imaplib.IMAP4.idmethod, a wrapper for theIDcommand (2971). (Contributed by Serhiy Storchaka in98092.) - Add the
~imaplib.IMAP4.movemethod, a wrapper for theMOVEcommand (6851). (Contributed by Serhiy Storchaka in77508.) - Add the
~imaplib.IMAP4.login_plainmethod, which authenticates using thePLAINSASL mechanism (4616) and supports non-ASCII user names and passwords. (Contributed by Przemysław Buczkowski and Serhiy Storchaka in89869.) - Non-ASCII mailbox names are now automatically encoded as modified UTF-7 (
3501, section 5.1.3) in the default mode, so international mailbox names can be passed as ordinarystrwithout enablingUTF8=ACCEPT(under which they are sent as UTF-8). (Contributed by Serhiy Storchaka in49555.) - The
~imaplib.IMAP4.copy,~imaplib.IMAP4.move,~imaplib.IMAP4.fetch,~imaplib.IMAP4.store,~imaplib.IMAP4.search,~imaplib.IMAP4.sort,~imaplib.IMAP4.threadand~imaplib.IMAP4.expungemethods now accept a keyword-only uid argument that selects the correspondingUIDcommand, as a more convenient alternative to~imaplib.IMAP4.uid. (Contributed by Serhiy Storchaka in153502.) ~imaplib.IMAP4.search,~imaplib.IMAP4.sortand~imaplib.IMAP4.thread(and the correspondinguidcommands) now encodestrsearch criteria to the declared charset, so international search text can be passed as an ordinarystr. When charset isNone(as it must be underUTF8=ACCEPT), the criteria are sent using the connection encoding instead. (Contributed by Serhiy Storchaka in153494.)- Command methods now accept structured arguments, so the module takes care of quoting instead of the caller. A message_set and lists of flags or other atoms can be passed as sequences instead of preformatted strings, and the
~imaplib.IMAP4.search,~imaplib.IMAP4.fetch,~imaplib.IMAP4.sort,~imaplib.IMAP4.threadand~imaplib.IMAP4.uidmethods accept a params keyword argument that substitutes and quotes?placeholders, in the manner ofsqlite3parameter substitution. (Contributed by Serhiy Storchaka in153521.)
io
- Add
io.BytesIO.peekmethod to read without advancing position. (Contributed by Marcel Martin in90533.)
ipaddress
- Add
IPv4Network.next_network() <ipaddress.IPv4Network.next_network>andIPv6Network.next_network() <ipaddress.IPv6Network.next_network>methods to find the next nearest network with a specific prefix size. (Contributed by Faisal Mahmood in87027.)
logging
~logging.handlers.TimedRotatingFileHandlernow uses the creation time instead of the last modification time of an existing log file as the basis for the first rotation after handler creation, if supported by the OS and file system. This allows it to be used in short-running programs that start and end before the rotation interval expires. (Contributed by Iván Márton and Serhiy Storchaka in84649.)
lzma
- Add support of new BCJ filters ARM64 and RISC-V via
!lzma.FILTER_ARM64and!lzma.FILTER_RISCV. Note that the new filters will work only if the runtime library supports them. ARM64 filter requireslzma5.4.0 or newer while RISC-V requires 5.6.0 or newer. (Contributed by Chien Wong in115988.) - Added constants
~lzma.LZMA_VERSION,~lzma.lzma_version,~lzma.LZMA_VERSION_INFO, and~lzma.lzma_version_info, which provide information about the version of the lzma library in use. (Contributed by Serhiy Storchaka in117404.)
math
- Added trigonometric functions that work in units of half turns, rather than radians. The new functions
math.acospi,math.asinpi,math.atanpi, andmath.atan2pireturn half-turn angles. The new functionsmath.cospi,math.sinpi, andmath.tanpitake half-turn angle arguments. These functions are recommended by IEEE 754-2019 and standardized in C23. (Contributed by Jeff Epler in150534.)
multiprocessing
- Add the optional buffersize parameter to
multiprocessing.pool.Pool.imapandmultiprocessing.pool.Pool.imap_unorderedto limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterable pauses until a result is yielded from the buffer. To fully utilize pool's capacity when using this feature, set buffersize at least to the number of processes in pool (to consume iterable as you go), or even higher (to prefetch the nextN=buffersize-processesarguments). (Contributed by Oleksandr Baltian in136871.)
os
- Add
os.pidfd_getfdfor duplicating a file descriptor from another process via a pidfd. Available on Linux 5.6+. (Contributed by Maurycy Pawłowski-Wieroński in149464.) - The following functions are now available on Android:
os.chroot,os.initgroups,os.setegid,os.seteuid,os.setgid,os.setregid,os.setresgid,os.setresuid,os.setreuid, andos.setuid. Calling them without sufficient privileges now raisesPermissionErrorinstead of the functions being unavailable. (Contributed by Md Arif in152936.) os.readlinknow accepts a file descriptor referring to a symlink on Linux, Android, macOS and iOS. (Contributed by OOTS in157899.)
pydoc
- Modernize the HTML output of
pydoc. The pages generated by thepydocHTTP server now use semantic HTML5 markup and a new style sheet based on the python-docs-theme used by docs.python.org, with dark mode support. Class members inherited from other classes are collapsed by default. (Contributed by Serhiy Storchaka in153906.)
pickle
- Weak references (
weakref.ref),weakref.WeakMethod,weakref.WeakSet,weakref.WeakValueDictionaryandweakref.WeakKeyDictionarycan now be pickled if the weakly referenced objects are strongly referenced elsewhere in the same pickle; otherwise pickling raisespickle.PicklingError.!WeakMethodand!WeakSetcan now also be copied. (Contributed by Serhiy Storchaka in74876.)
quopri
quopri.decode,quopri.decodestringandbinascii.a2b_qpgained a strip_ws parameter. When true, trailing whitespace is stripped from each line while decoding, as required by2045for a quoted-printable body. (Contributed by Serhiy Storchaka in62222.)
re
renow supports set operations and nested sets in character classes, as described in Unicode Technical Standard #18: set difference ([A--B]), intersection ([A&&B]) and union ([A||B]), where an operand may be a nested set written in square brackets. For example,[a-z--[aeiou]]matches an ASCII lowercase consonant. (Contributed by Serhiy Storchaka in152100.)- Regular expressions now support Unicode property escapes
\p{...}and\P{...}, which match a character by a Unicode property -- for example\p{Lu}(an uppercase letter),\p{Cased}or\p{ASCII}. Seethe regular expression syntax <re-syntax>for the supported properties. (Contributed by Serhiy Storchaka in95555.)
readline
- Added constants
~readline.READLINE_VERSION_INFO,~readline.readline_version_infoand~readline.readline_version, which provide information about the version of the Readline library in use. (Contributed by Serhiy Storchaka in157485.)
shlex
- Add keyword-only parameter force to
shlex.quoteto force quoting a string, even if it is already safe for a shell without being quoted. (Contributed by Jay Berry in148846.)
shutil
- Add keyword-only copy_dir_stat parameter to
shutil.copytree: set it to false to skip copying directory metadata withshutil.copystat, e.g. when copying a read-only tree. (Contributed by Łukasz Langa in89721.) shutil.unpack_archivecan now unpack wheel files using thewhlformat. (Contributed by Emma Harper Smith and Stan Ulbrych in84027.)
socket
- The
socket.sethostnamefunction is now available on Android. Calling it without sufficient privileges now raisesPermissionErrorinstead of the function being unavailable. (Contributed by Md Arif in152936.)
sqlite3
sqlite3.Blobnow supports negative-step slices for reading and writing (for example,blob[9:0:-2]). Previously, such slices would raiseSystemErrororValueError. (Contributed by Jiseok CHOI in150449.)- Added constants
~sqlite3.SQLITE_VERSIONand~sqlite3.SQLITE_VERSION_INFOwhich provide information about the version of the SQLite library that was used for building the module.~sqlite3.sqlite_version_infois now a named tuple. (Contributed by Serhiy Storchaka in157470.)
ssl
- Added support for
Encrypted Client Hello <ssl-encrypted-client-hello>(ECH) with OpenSSL 4.0 or later. Clients can supply an ECHConfigList discovered through DNS, for example using a third-party library such asdnspythonto query HTTPS or SVCB records, as the ech_config argument of~ssl.SSLContext.wrap_socketand~ssl.SSLContext.wrap_bioor with~ssl.SSLContext.set_ech_config. Servers can use~ssl.SSLContext.load_ech_keysto load ECH private keys and their configurations from PEM files. (Contributed by Peter Bierma and Iain R. Learmonth in89730.) ssl.OPENSSL_VERSION_INFOis now a named tuple. Added~ssl.OPENSSL_API_VERSION_INFOwhich provides information about the version of the OpenSSL library that was used for building the module. (Contributed by Serhiy Storchaka in157513.)- The
sslmodule now rejects TLS certificate chains that contain one of a set of compromised eMudhra intermediate CA certificates. The affected certificates are identified by their public key, so cross-signed copies that reuse the same key are blocked as well. It is a defense-in-depth backstop that applies even when an application supplies its own root CA bundle, and regardless of whether the platform trust store has removed trust. (Contributed by Christian Heimes in160040for2026-115557.)
symtable
symtable.symtablenow accepts an AST object, like the built-incompile. (Contributed by Serhiy Storchaka in153844.)- Inlined list, set and dict comprehensions (
709) are now represented as their own symbol table entries, of type~symtable.SymbolTableType.INLINED_COMPREHENSION. Each such entry is a lexical child of the enclosing scope and records the comprehension's own locals, cells, and free names. It does not correspond to a separate compilation unit. For names loaded only inside an inlined list, set, or dict comprehension,symtable.Symbol.is_referencedcan now returnTrueon the enclosing function. (Contributed by Irit Katriel in124697.)
tkinter
- Added many
tkinter.ttk.Treeviewmethods wrapping the enhancedttk::treeviewwidget commands from Tk 9.1, such as~tkinter.ttk.Treeview.sort,~tkinter.ttk.Treeview.search,~tkinter.ttk.Treeview.expand,~tkinter.ttk.Treeview.collapse,~tkinter.ttk.Treeview.hide,~tkinter.ttk.Treeview.unhide, and methods for cell focus, selection and tagging. The~tkinter.ttk.Treeview.expandand~tkinter.ttk.Treeview.collapsemethods (without recursion) also work on Tk older than 9.1. (Contributed by Serhiy Storchaka in151910.) - Added constants
~tkinter.TCL_VERSION_INFOand~tkinter.TK_VERSION_INFO, named tuples with the versions of the Tcl and Tk libraries that were used for building the module. (Contributed by Serhiy Storchaka in157514.) - Added new
!tkinter.Textmethods~tkinter.Text.edit_canundoand~tkinter.Text.edit_canredowhich return whether an undo or redo is possible. (Contributed by Serhiy Storchaka in151674.) - Added new
!tkinter.Textmethods~tkinter.Text.syncand~tkinter.Text.pendingsyncwhich control and report the synchronization of the displayed view with the underlying text. (Contributed by Serhiy Storchaka in151675.) - Added the
ttk.Style.theme_styles <tkinter.ttk.Style.theme_styles>method which returns the list of styles defined in a theme. (Contributed by Serhiy Storchaka in151920.) - Added new
!tkinter.Canvasmethods~tkinter.Canvas.rcharswhich replaces the text or coordinates of canvas items, and~tkinter.Canvas.rotatewhich rotates the coordinates of canvas items. (Contributed by Serhiy Storchaka in151876.) - Added a
!validatemethod to the!tkinter.Entryand!tkinter.Spinboxwidgets, which forces an evaluation of the validation command. (Contributed by Serhiy Storchaka in151878.) - Added the
tkinter.Menu.postcascademethod, and the~tkinter.Misc.tk_scalingand~tkinter.Misc.tk_inactivemethods which respectively query or set the display scaling factor and report the user idle time. (Contributed by Serhiy Storchaka in151881.) - Added the
!tk_printmethod totkinter.Canvasandtkinter.Textwhich prints the contents of the widget using the native print dialog. It requires Tk 8.7/9.0 or newer. (Contributed by Serhiy Storchaka in153256.) - Added new window-management methods
~tkinter.Misc.winfo_isdark(dark mode detection),~tkinter.Wm.wm_iconbadge(application icon badge) and~tkinter.Wm.wm_stackorder(toplevel stacking order). (Contributed by Serhiy Storchaka in151874.) - Added the
~tkinter.Misc.tk_appname,~tkinter.Misc.tk_useinputmethodsand~tkinter.Misc.tk_caretmethods, exposing the application send name, the X Input Methods state and the input method caret location. (Contributed by Serhiy Storchaka in151886.) - Added support for more options in
!tkinter.PhotoImagemethods: the format parameter of~tkinter.PhotoImage.put, the metadata parameter of~tkinter.PhotoImage.put,~tkinter.PhotoImage.read,~tkinter.PhotoImage.writeand~tkinter.PhotoImage.data, and the withalpha parameter of~tkinter.PhotoImage.get. (Contributed by Serhiy Storchaka in151890.) - Added the
~tkinter.PhotoImage.redithermethod which recalculates the dithered image when its data was supplied in pieces. (Contributed by Serhiy Storchaka in151888.) tkinter.OptionMenunow accepts arbitrary!tkinter.Menubuttonoptions as keyword arguments, which can also override its default appearance. (Contributed by Serhiy Storchaka in101284.)- The
tkinter.simpledialogdialogs were modernized to match the look and feel of the native Tk dialogs.!tkinter.simpledialog.SimpleDialogand the~tkinter.simpledialog.askinteger,~tkinter.simpledialog.askfloatand~tkinter.simpledialog.askstringdialogs are now built from the themedtkinter.ttkwidgets instead of the classictkinterwidgets; the!tkinter.simpledialog.Dialogbase class still defaults to the classic widgets for compatibility. Both!Dialogand!SimpleDialoggained a use_ttk parameter that selects between the classic Tk widgets and the themed ttk widgets.!SimpleDialogalso gained bitmap and detail parameters, draws the standard icons with themed images in the ttk version, and accepts mappings of button options as buttons entries. (Contributed by Serhiy Storchaka in59396.) - The
!tkinter.filedialog.FileDialogdialog and its!tkinter.filedialog.LoadFileDialogand!tkinter.filedialog.SaveFileDialogsubclasses are now built from the themedtkinter.ttkwidgets by default instead of the classictkinterwidgets, and gained a use_ttk parameter to select between them. (Contributed by Serhiy Storchaka in59396.) - Added the
tkinter.systraymodule which provides the~tkinter.systray.SysTrayIconclass as an interface to the system tray icon and the~tkinter.systray.notifyfunction which sends a desktop notification. They require Tk 8.7/9.0 or newer. (Contributed by Serhiy Storchaka in153259.) tkinter.scrolledtext.ScrolledTextgained a use_ttk parameter to use the themedtkinter.ttkframe and scroll bar instead of the classictkinterwidgets. (Contributed by Serhiy Storchaka in59396.)tkinter.font.Fontcan now wrap a font description without creating a new named font, by passing it as font withexists=Trueand no name. This avoids a loss of precision in~tkinter.font.Font.actual,~tkinter.font.Font.measureand~tkinter.font.Font.metrics. (Contributed by Serhiy Storchaka in143990.)- Added the
tkinter.fontchoosermodule which provides the~tkinter.fontchooser.FontChooserclass as an interface to the native font selection dialog. (Contributed by Serhiy Storchaka in72880.) - Values of several Tcl object types returned by
tkinterare now converted to the corresponding Python type instead of being wrapped in a!_tkinter.Tcl_Obj:index,window,nsNameandparsedVarNameobjects tostr, andpixelscreen distances with no unit suffix tointorfloat. (Contributed by Serhiy Storchaka in153513.)
turtle
- Translations of the
turtledocstrings are now distributed on PyPI in theturtle-translationspackage. Additionally, added thePYTHON_TURTLE_LANGenvironment variable to select the language. (Contributed by Stan Ulbrych in156360.)
unicodedata
- The Unicode database has been updated to Unicode 18.0.0.
uuid
uuid.UUID,uuid.uuid4, anduuid.uuid7now have C implementations, with a pure Python fallback. In microbenchmarks, UUIDv4 and UUIDv7 generation are approximately 15 and 30 times faster, respectively, than the pure Python implementations. UUID construction and string conversion are also faster; seewhatsnew316-uuid-optimizationsfor the benchmark results. (Contributed by Yury Selivanov in139123.)
xml
- Add support for multiple multi-byte encodings in the
XML parser <xml.parsers.expat>: "cp932", "cp949", "cp950", "Big5", "EUC-JP", "GB2312", "GBK", "johab", and "Shift_JIS". Add partial support (only BMP characters) for multi-byte encodings "Big5-HKSCS", "EUC_JIS-2004", "EUC_JISX0213", "Shift_JIS-2004", "Shift_JISX0213", "utf-8-sig" and non-standard aliases like "UTF8" (without hyphen). The parser now raisesValueErrorfor known unsupported multi-byte encodings such as "ISO-2022-JP" or "raw-unicode-escape" instead of failing later, when encountering non-ASCII data. (Contributed by Serhiy Storchaka in62259.) xml.dom.minidomnow conforms closer to the DOM Level 1 specification. It checks names passed to the factory methods, rejects inserting or setting a node created by another document or making a node a descendant of itself, rejects a second element or document type child of a document and a notation child of a document fragment, reports attributes defaulted in the DTD and whether an attribute was given in the start tag, and implements!EntityReferencenodes and!Document.createEntityReference. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.)xml.dom.minidomnow validates namespaces in the factory methods~xml.dom.Document.createElementNS,~xml.dom.Document.createAttributeNSand~xml.dom.Element.setAttributeNS.~xml.dom.NamespaceErris now raised for a malformed qualified name, for a prefix with an empty namespace, and for illegal use of thexmlandxmlnsprefixes. (Contributed by Serhiy Storchaka in156665.)~xml.dom.minidom.Node.toprettyxmlinxml.dom.minidomand~xml.etree.ElementTree.indentinxml.etree.ElementTreeno longer add whitespace inside an element which is marked withxml:space="preserve"or which contains text.!toprettyxmlalso takes into account the content model declared in the DTD. (Contributed by Serhiy Storchaka in81623.)- Add
!GetSpecifiedAttributeCountmethod to theXML parser <xml.parsers.expat>objects. It tells how many of the reported attributes were given in the start tag rather than defaulted from the DTD. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.) - The
~xml.dom.minidom.Node.writexml,~xml.dom.minidom.Node.toxmland~xml.dom.minidom.Node.toprettyxmlmethods now work for!DocumentFragmentnodes inxml.dom.minidom. (Contributed by Serhiy Storchaka in54092.) ~xml.etree.ElementTree.XMLPullParserand~xml.etree.ElementTree.iterparsenow support the target parameter. The reported object is the value returned by the corresponding method of the target, so a large document can be parsed incrementally without building a tree for it. (Contributed by Serhiy Storchaka in63102.)- Added constant
~xml.parsers.expat.VERSION_INFOin theXML parser <xml.parsers.expat>module, which provides information about the version of the Expat library that was used for building the module.~xml.parsers.expat.version_infois now a named tuple. (Contributed by Serhiy Storchaka in157473.)
zipfile
- Add
ZipFile.remove() <zipfile.ZipFile.remove>to remove a member from an archive's central directory, andZipFile.repack() <zipfile.ZipFile.repack>to reclaim the space used by the local file entries of removed members. (Contributed by Danny Lin in51067.)
zlib
- Added constants
~zlib.ZLIB_VERSION_INFO,~zlib.zlib_version_info, and~zlib.ZLIBNG_VERSION_INFO, which provide information about the version of the zlib and the zlib-ng libraries in use. Added~zlib.zlib_versionas an alias of~zlib.ZLIB_RUNTIME_VERSION. (Contributed by Serhiy Storchaka in117404.)
Optimizations
datetime and time
datetime.datetime.strptime,datetime.date.strptime,datetime.time.strptime, andtime.strptimeare faster for common numeric formats such as%Y-%m-%dand%Y-%m-%d %H:%M:%S. (Contributed by Paul Ganssle in158252, based on work by Stan Ulbrych.)
re
- Character class escapes (
\d,\D,\s,\S,\wand\W) outside a character set, and character sets containing a single such escape (such as[\d]or[^\s]), are now compiled to a singleCATEGORYopcode instead of being wrapped in anINblock. This speeds up matching of patterns such as\d+and reduces the size of the compiled byte code. (Contributed by Serhiy Storchaka in152033and Pieter Eendebak in152056.)
uuid
-
C implementations accelerate UUID generation, construction, and string conversion. Microbenchmarks comparing the C and pure Python implementations measured the following speedups:
Operation Speedup uuid.uuid4generation15.01x uuid.uuid7generation29.64x uuid.UUIDfrom a string6.76x uuid.UUIDfrom bytes5.16x strconversion of a UUID6.66x (Contributed by Yury Selivanov in
139123.)
Removed
annotationlib
- The
!annotationlib.ForwardRef._evaluatemethod which has been deprecated since Python 3.14. Useannotationlib.ForwardRef.evaluateortyping.evaluate_forward_refinstead.
array
- The
'u'format code (wchar_t) which has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use'w'format code instead (Py_UCS4, always 4 bytes).
asyncio
- The
!asyncio.iscoroutinefunctionwhich has been deprecated since Python 3.14. Useinspect.iscoroutinefunctioninstead. - The event loop policy system, including the
!asyncio.AbstractEventLoopPolicy,!asyncio.DefaultEventLoopPolicy,!asyncio.WindowsSelectorEventLoopPolicyand!asyncio.WindowsProactorEventLoopPolicyclasses and the!asyncio.get_event_loop_policyand!asyncio.set_event_loop_policyfunctions, which have been deprecated since Python 3.14. Useasyncio.runorasyncio.Runnerwith a custom loop_factory instead.
functools
- Remove support for calling the Python implementation of
functools.reducewith function or sequence as keyword arguments, deprecated since Python 3.14. These parameters are now positional-only. (Contributed by Nikita Sobolev in149537.)
logging
- Remove support for custom logging handlers with the strm argument, deprecated since Python 3.14. Define handlers with the stream argument instead. (Contributed by Nikita Sobolev in
149598.)
mimetypes
- Remove support for undotted extensions in
mimetypes.MimeTypes.add_type, deprecated since Python 3.14. Valid extensions must now start with a'.'or be empty; undotted extensions raise aValueError. (Contributed by Nikita Sobolev in149720.)
shutil
- The
!ExecErrorexception which has been deprecated since Python 3.14. It has not been used by any function in!shutilsince Python 3.4. (Contributed by Stan Ulbrych in149567.)
symtable
- The
!symtable.Class.get_methodsmethod which has been deprecated since Python 3.14.
sys
- The
!_enablelegacywindowsfsencodingfunction which has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead. (Contributed by Stan Ulbrych in149595.)
sysconfig
- The
!sysconfig.expand_makefile_varsfunction which has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_pathsinstead. (Contributed by Stan Ulbrych in149499.)
tarfile
- The undocumented and unused
!tarfile.TarFile.tarfileattribute has been deprecated since Python 3.13.
xml.etree.ElementTree
- The undocumented
!xml.etree.ElementTree.ElementTree.write_c14nmethod and the support ofmethod="c14n"in~xml.etree.ElementTree.ElementTree.writeand~xml.etree.ElementTree.tostring. They never worked and always raisedValueError. Usexml.etree.ElementTree.canonicalizeinstead. (Contributed by Daniel Hillier in118318.)
Deprecated
New deprecations
abc:abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractproperty, soft-deprecated since Python 3.3, now raise aDeprecationWarning. These classes will be removed in Python 3.21; useabc.abstractmethodwithclassmethod,staticmethod, andpropertyrespectively instead.
ast:- Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, deprecated since Python 3.9, are no longer imported byfrom ast import *and issue a deprecation warning on use. The classes are slated for removal in Python 3.21. These types are not generated by the parser or accepted by the code generator. - The
dimsproperty ofast.Tupleobjects, deprecated since Python 3.9, now issues a deprecation warning on use. This property is slated for removal in 3.21. Useast.Tuple.eltsinstead.
- Classes
__author__,__credits__,__copyright__and__date__:-
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.)
-
functools:- Using a return annotation to infer the dispatch type for
functools.singledispatchorfunctools.singledispatchmethodnow emits aDeprecationWarningand 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:- The
'F'and'D'type codes, soft-deprecated since Python 3.15, are now deprecated. These codes will be removed in Python 3.21. Use the two-letter forms'Zf'and'Zd'instead. (Contributed by Sergey B Kirpichev in121249.)
- The
tempfile:- The private
tempfile._TemporaryFileWrappername is deprecated and is slated for removal in Python 3.21. Use the new publictempfile.TemporaryFileWrapperinstead, which is the return type oftempfile.NamedTemporaryFile.
- The private
tkinter:tkinter.filedialog.askopenfilesis deprecated and slated for removal in Python 3.19. Opening several files at once is error-prone, and the returned list cannot be used in awithstatement. 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.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.
Porting to Python 3.16
This section lists previously described changes and other bugfixes that may require changes to your code.
- In
tkinter, the name parameter of the~tkinter.Misc.wait_variable,~tkinter.Misc.setvarand~tkinter.Misc.getvarmethods and the value parameter of!setvarare now required. Calling these methods without them, which formerly defaulted to'PY_VAR'and'1', now raisesTypeError. (Contributed by Serhiy Storchaka in152587.) uuid.UUIDnow consistently raisesTypeErrorwhen the bytes or bytes_le argument is not abytesobject. Previously, some invalid inputs raisedAssertionErrororValueError. (Contributed by Yury Selivanov in139123.)xml.dom.minidomnow raises~xml.dom.InvalidCharacterErrfor a name which is not a valid XML name,~xml.dom.WrongDocumentErrfor inserting or setting a node created by another document,~xml.dom.InuseAttributeErrfor setting an attribute node which belongs to another element, and~xml.dom.HierarchyRequestErrfor inserting a node into itself or its descendant. It also rejects a second element or document type child of a document and a notation child of a document fragment. Such operations formerly succeeded and produced an invalid document or an endless loop. On the other hand,!Element.removeAttributeand!Element.removeAttributeNSno longer raise~xml.dom.NotFoundErrif there is no matching attribute. Attributes defaulted in the DTD are no longer omitted when parsing. (Contributed by Jason Orendorff and Serhiy Storchaka in44871.)xml.dom.minidomnow raises~xml.dom.NamespaceErrfor a malformed qualified name, for a prefix with an empty namespace, and for illegal use of thexmlandxmlnsprefixes. Such operations formerly succeeded and produced an invalid document. (Contributed by Serhiy Storchaka in156665.)~xml.dom.minidom.Node.toprettyxmlinxml.dom.minidomand~xml.etree.ElementTree.indentinxml.etree.ElementTreeno longer add whitespace inside an element which is marked withxml:space="preserve"or which contains text, because this changed the content of the element.!toprettyxmlalso takes into account the content model declared in the DTD. (Contributed by Serhiy Storchaka in81623.)- On Windows, seeking a pipe now fails instead of silently appearing to succeed:
os.lseekand~io.IOBase.seekraiseOSError, and~io.IOBase.seekablereturnsFalse. As a consequence, opening a pipe in a read-write binary mode ('r+b'or'w+b') now raisesio.UnsupportedOperationunless buffering is disabled. (Contributed by An Long in86768.)
Build changes
-
Remove the bundled copy of the libmpdec decimal library from the CPython source tree to simplify maintenance and updates. The
decimalmodule will now unconditionally use the system's libmpdec decimal library. Also remove the now unused!--with-system-libmpdecconfigureflag. This change has no impact on binary releases of Python, which have been built against a separate copy of libmpdec for the past several releases.(Contributed by Sergey B Kirpichev in
115119.) -
Add a
--with-build-details-suffixconfigure flag to allow Linux distributions that co-install multiple versions of Python in the same tree to avoidbuild-details.jsonclashes.(Contributed by Stefano Rivera in
131372.) -
Add the
--with-cursesconfigureoption to select the curses backend for thecursesandcurses.panelmodules. In addition toncurseswandncurses, it can now build against the system's nativecurseslibrary (for example on NetBSD or Solaris), with wide-character support when the library provides it.--without-cursesexcludes the modules from the build.(Contributed by Serhiy Storchaka in
136687.) -
Add the
--with-zliband--with-bzip2configureoptions to select the zlib and bzip2 implementations used to build thezlibandbz2modules. In addition to the default system libraries, they can build against zlib-rs and libbzip2-rs, and--with-zlib=zlib-ngverifies that the detected zlib is zlib-ng.--without-zliband--without-bzip2exclude the modules from the build.(Contributed by Stan Ulbrych in
139314.) -
Add the
--with-hwaddress-sanitizerconfigureoption to build with HWAddressSanitizer.(Contributed by Stan Ulbrych, Florian Mayer and AnnaAr321 in
156049.)
C API changes
New features
- Add
Py_HashBufferto the limited C API. (Contributed by Victor Stinner in148233.) - Add
Py_SETREFandPy_XSETREFmacros to the limited C API. (Contributed by Nathan Goldbaum and Victor Stinner in158842.)
Porting to Python 3.16
PyType_ClearCacheis now a no-op as the type cache is now implemented per-type. It still returns the current version tag.- Functions reading marshalled data from a
FILE*, such asPyMarshal_ReadObjectFromFile, now raiseOSErrorfor I/O errors andKeyboardInterruptfor interrupted reading, instead ofEOFError. (Contributed by Serhiy Storchaka in155907.) PyMarshal_WriteLongToFileandPyMarshal_WriteObjectToFilenow set the error indicator for I/O errors and interrupted writing, instead of ignoring them.PyMarshal_WriteObjectToFilenow also sets the error indicator if the value cannot be marshalled. (Contributed by Serhiy Storchaka in155907.)_Py_c_absno longer setserrnoto zero on success, but rather leaves it unchanged. (Contributed by Sergey B Kirpichev in155526.)
Deprecated C APIs
PyGen_New,PyGen_NewWithQualName,PyCoro_New, andPyAsyncGen_Neware deprecated. They are scheduled for removal in 3.18.- Deprecate
PyInitConfig_GetExitCode,PyStatus_Exit, andPyStatus_IsExitfunctions, andPyStatus.exitcodemember.Py_InitializeFromInitConfigandPy_InitializeFromConfigcan no longer return an exit code. Instead, if a command line option wants to exit Python, the option is now processed inPy_RunMain. (Contributed by Victor Stinner in158080.) PyModule_GetFilenameis no longer deprecated, but usingPyModule_GetFilenameObjectinstead is still recommended. (Contributed by Victor Stinner in154757.)- Soft deprecate functions modifying Unicode strings:
PyUnicode_New,PyUnicode_CopyCharacters,PyUnicode_Fill,PyUnicode_Resize,PyUnicode_WRITEandPyUnicode_WriteChar. Use the saferPyUnicodeWriterAPI instead. (Contributed by Victor Stinner in157710.)
Pending removal in Python 3.18
-
The following private functions are deprecated and planned for removal in Python 3.18:
!_PyBytes_Join: usePyBytes_Join.!_PyDict_GetItemStringWithError: usePyDict_GetItemStringRef.!_PyDict_Pop(): usePyDict_Pop.!_PyLong_Sign(): usePyLong_GetSign.!_PyLong_FromDigitsand!_PyLong_New: usePyLongWriter_Create.!_PyThreadState_UncheckedGet: usePyThreadState_GetUnchecked.!_PyUnicode_AsString: usePyUnicode_AsUTF8.!_PyUnicodeWriter_Init: replace_PyUnicodeWriter_Init(&writer)withwriter = PyUnicodeWriter_Create(0) <PyUnicodeWriter_Create>.!_PyUnicodeWriter_Finish: replace_PyUnicodeWriter_Finish(&writer)withPyUnicodeWriter_Finish(writer) <PyUnicodeWriter_Finish>.!_PyUnicodeWriter_Dealloc: replace_PyUnicodeWriter_Dealloc(&writer)withPyUnicodeWriter_Discard(writer) <PyUnicodeWriter_Discard>.!_PyUnicodeWriter_WriteChar: replace_PyUnicodeWriter_WriteChar(&writer, ch)withPyUnicodeWriter_WriteChar(writer, ch) <PyUnicodeWriter_WriteChar>.!_PyUnicodeWriter_WriteStr: replace_PyUnicodeWriter_WriteStr(&writer, str)withPyUnicodeWriter_WriteStr(writer, str) <PyUnicodeWriter_WriteStr>.!_PyUnicodeWriter_WriteSubstring: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)withPyUnicodeWriter_WriteSubstring(writer, str, start, end) <PyUnicodeWriter_WriteSubstring>.!_PyUnicodeWriter_WriteASCIIString: replace_PyUnicodeWriter_WriteASCIIString(&writer, str, size)withPyUnicodeWriter_WriteASCII(writer, str, size) <PyUnicodeWriter_WriteASCII>.!_PyUnicodeWriter_WriteLatin1String: replace_PyUnicodeWriter_WriteLatin1String(&writer, str, size)by decoding the string withPyUnicode_DecodeLatin1, writing the result withPyUnicodeWriter_WriteStr, and releasing the result withPy_DECREF.!_PyUnicodeWriter_Prepare: (no replacement).!_PyUnicodeWriter_PrepareKind: (no replacement).!_Py_HashPointer: usePy_HashPointer.!_Py_fopen_obj: usePy_fopen.PyGen_New: (no replacement).PyGen_NewWithQualName: (no replacement).PyCoro_New: (no replacement).PyAsyncGen_New: (no replacement).
The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older. (Contributed by Victor Stinner in
128863.)
Pending removal in Python 3.19
456embedders support for the string hashing scheme definition.
Pending removal in Python 3.20
!_PyObject_CallMethodId,!_PyObject_GetAttrIdand!_PyUnicode_FromIdare deprecated since 3.15 and will be removed in 3.20. Instead, usePyUnicode_InternFromString()and cache the result in the module state, then callPyObject_CallMethodorPyObject_GetAttr. (Contributed by Victor Stinner in141049.)- The
cvalfield inPyComplexObject(128813). UsePyComplex_AsCComplexandPyComplex_FromCComplexto convert a Python complex number to/from the CPy_complexrepresentation. - Macros
!Py_MATH_PIland!Py_MATH_El.
Pending removal in future versions
The following APIs are deprecated and will be removed, although there is currently no date scheduled for their removal.
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch: UsePyErr_GetRaisedExceptioninstead.PyErr_NormalizeException: UsePyErr_GetRaisedExceptioninstead.PyErr_Restore: UsePyErr_SetRaisedExceptioninstead.PyOS_AfterFork: UsePyOS_AfterFork_Childinstead.PySlice_GetIndicesEx: UsePySlice_UnpackandPySlice_AdjustIndicesinstead.PyUnicode_READY: Unneeded since Python 3.12!PyErr_Display: UsePyErr_DisplayExceptioninstead.!_PyErr_ChainExceptions: Use!_PyErr_ChainExceptions1instead.!PyBytesObject.ob_shashmember: callPyObject_Hashinstead.- Thread Local Storage (TLS) API:
PyThread_create_key: UsePyThread_tss_allocinstead.PyThread_delete_key: UsePyThread_tss_freeinstead.PyThread_set_key_value: UsePyThread_tss_setinstead.PyThread_get_key_value: UsePyThread_tss_getinstead.PyThread_delete_key_value: UsePyThread_tss_deleteinstead.PyThread_ReInitTLS: Unneeded since Python 3.7.
Removed C APIs
-
Remove 21 global configuration variables, deprecated in Python 3.12. To initialize Python, the
PyInitConfig C API <pyinitconfig_api>can be used instead. To read these variables at runtime,PyConfig_Getcan be used instead. Removed variables with theirPyInitConfig C API <pyinitconfig_api>andPyConfig_Getreplacement:!Py_DebugFlag: Use"parser_debug"instead.!Py_VerboseFlag: Use"verbose"instead.!Py_QuietFlag: Use"quiet"instead.!Py_InteractiveFlag: Use"interactive"instead.!Py_InspectFlag: Use"inspect"instead.!Py_OptimizeFlag: Use"optimization_level"instead.!Py_NoSiteFlag: Use"site_import"instead (opposite value).!Py_BytesWarningFlag: Use"bytes_warning"instead.!Py_FrozenFlag: Use"pathconfig_warnings"instead (opposite value).!Py_IgnoreEnvironmentFlag: Use"use_environment"instead (opposite value).!Py_DontWriteBytecodeFlag: Use"write_bytecode"instead (opposite value).!Py_NoUserSiteDirectory: Use"user_site_directory"instead (opposite value).!Py_UnbufferedStdioFlag: Use"buffered_stdio"instead (opposite value).!Py_HashRandomizationFlag: Use"hash_seed"instead.!Py_IsolatedFlag: Use"isolated"instead.!Py_LegacyWindowsFSEncodingFlag: Use"legacy_windows_fs_encoding"instead.!Py_LegacyWindowsStdioFlag: Use"legacy_windows_stdio"instead.!Py_FileSystemDefaultEncoding,!Py_HasFileSystemDefaultEncoding: Use"filesystem_encoding"instead.!Py_FileSystemDefaultEncodeErrors: Use"filesystem_errors"instead.!Py_UTF8Mode: Use"utf8_mode"instead.
(Contributed by Victor Stinner in
158001.) -
Remove
!PyEval_InitThreadsfunction which did nothing since Python 3.7 and was deprecated since Python 3.9. (Contributed by Victor Stinner in154757.) -
Remove
!Py_SetProgramNameand!Py_SetPythonHomefunctions, deprecated since Python 3.11. Instead, usePyInitConfig C API <pyinitconfig_api>to set respectively"program_name"and"home". (Contributed by Victor Stinner in158001.) -
Remove
!PySys_SetArgvand!PySys_SetArgvExfunctions, deprecated since Python 3.11. Instead, set directlysys.argv, and maybe alsosys.path. (Contributed by Victor Stinner in158001.) -
The
!PyUnstable_ExecutableKindsarray, as well as the macros!PyUnstable_EXECUTABLE_KIND_SKIP,!PyUnstable_EXECUTABLE_KIND_PY_FUNCTION,!PyUnstable_EXECUTABLE_KIND_BUILTIN_FUNCTION,!PyUnstable_EXECUTABLE_KIND_METHOD_DESCRIPTORand!PyUnstable_EXECUTABLE_KINDS, were removed.(Contributed by Peters Bierma and Viktorin in
152105.)
谢谢你的反馈!