This article explains the new features in Python 3.9, compared to 3.8.

For full details, see the changelog.

Prerelease users should be aware that this document is currently in draft form. It will be updated substantially as Python 3.9 moves towards release, so it’s worth checking back even after reading earlier versions.

More generally, try to run your tests in the Python Development Mode which helps to prepare your code to make it compatible with the next Python version.

Aliases to Abstract Base Classes in the collections module, like collections.Mapping alias to collections.abc.Mapping , are kept for one last release for backward compatibility. They will be removed from Python 3.10.

It has been decided to keep a few backward compatibility layers for one last release, to give more time to Python projects maintainers to organize the removal of the Python 2 support and add support for Python 3.9.

Test your application with the -W default command-line option to see DeprecationWarning and PendingDeprecationWarning , or even with -W error to treat them as errors. Warnings Filter can be used to ignore warnings from third-party code.

When Python 2.7 was still supported, many functions were kept for backward compatibility with Python 2.7. With the end of Python 2.7 support, these backward compatibility layers have been removed, or will be removed soon. Most of them emitted a DeprecationWarning warning for several years. For example, using collections.Mapping instead of collections.abc.Mapping emits a DeprecationWarning since Python 3.3, released in 2012.

See PEP 617 for more details. (Contributed by Guido van Rossum, Pablo Galindo and Lysandros Nikolaou in bpo-40334 .)

In Python 3.10, the old parser will be deleted and so will all functionality that depends on it (primarily the parser module, which has long been deprecated). In Python 3.9 only, you can switch back to the LL(1) parser using a command line switch ( -X oldparser ) or an environment variable ( PYTHONOLDPARSER=1 ).

The ast module uses the new parser and produces the same AST as the old parser.

Python 3.9 uses a new parser, based on PEG instead of LL(1) . The new parser’s performance is roughly comparable to that of the old parser, but the PEG formalism is more flexible than LL(1) when it comes to designing new language features. We’ll start using this flexibility in Python 3.10 and later.

See PEP 585 for more details. (Contributed by Guido van Rossum, Ethan Smith, and Batuhan Taşkaya in bpo-39481 .)

In type annotations you can now use built-in collection types such as list and dict as generic types instead of importing the corresponding capitalized types (e.g. List or Dict ) from typing . Some other types in the standard library are also now generic, for example queue.Queue .

str.removeprefix(prefix) and str.removesuffix(suffix) have been added to easily remove an unneeded prefix or a suffix from a string. Corresponding bytes , bytearray , and collections.UserString methods have also been added. See PEP 616 for a full description. (Contributed by Dennis Sweeney in bpo-39939 .)

Improved help for the typing module. Docstrings are now shown for all special forms and special generic aliases (like Union and List ). Using help() with generic alias like List[int] will show the help for the correspondent concrete type ( list in this case). (Contributed by Serhiy Storchaka in bpo-40257 .)

Any valid expression can now be used as a decorator . Previously, the grammar was much more restrictive. See PEP 614 for details. (Contributed by Brandt Bucher in bpo-39702 .)

"".replace("", s, n) now returns s instead of an empty string for all non-zero n . It is now consistent with "".replace("", s) . There are similar changes for bytes and bytearray objects. (Contributed by Serhiy Storchaka in bpo-28029 .)

By default, for best performance, the errors argument is only checked at the first encoding/decoding error and the encoding argument is sometimes ignored for empty strings. (Contributed by Victor Stinner in bpo-37388 .)

In the Python Development Mode and in debug build, the encoding and errors arguments are now checked for string encoding and decoding operations. Examples: open() , str.encode() and bytes.decode() .

Python now gets the absolute path of the script filename specified on the command line (ex: python3 script.py ): the __file__ attribute of the __main__ module became an absolute path, rather than a relative path. These paths now remain valid after the current directory is changed by os.chdir() . As a side effect, the traceback also displays the absolute path for __main__ module frames in this case. (Contributed by Victor Stinner in bpo-20443 .)

__import__() now raises ImportError instead of ValueError , which used to occur when a relative import went past its top-level package. (Contributed by Ngalim Siregar in bpo-37444 .)

Add the graphlib that contains the graphlib.TopologicalSorter class to offer functionality to perform topological sorting of graphs. (Contributed by Pablo Galindo, Tim Peters and Larry Hastings in bpo-17005 .)

As a fall-back source of data for platforms that don’t ship the IANA database, the tzdata module was released as a first-party package – distributed via PyPI and maintained by the CPython core team.

The zoneinfo module brings support for the IANA time zone database to the standard library. It adds zoneinfo.ZoneInfo , a concrete datetime.tzinfo implementation backed by the system’s time zone data.

Improved Modules¶

ast¶ Added the indent option to dump() which allows it to produce a multiline indented output. (Contributed by Serhiy Storchaka in bpo-37995.) Added ast.unparse() as a function in the ast module that can be used to unparse an ast.AST object and produce a string with code that would produce an equivalent ast.AST object when parsed. (Contributed by Pablo Galindo and Batuhan Taskaya in bpo-38870.) Added docstrings to AST nodes that contains the ASDL signature used to construct that node. (Contributed by Batuhan Taskaya in bpo-39638.)

asyncio¶ Due to significant security concerns, the reuse_address parameter of asyncio.loop.create_datagram_endpoint() is no longer supported. This is because of the behavior of the socket option SO_REUSEADDR in UDP. For more details, see the documentation for loop.create_datagram_endpoint() . (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in bpo-37228.) Added a new coroutine shutdown_default_executor() that schedules a shutdown for the default executor that waits on the ThreadPoolExecutor to finish closing. Also, asyncio.run() has been updated to use the new coroutine. (Contributed by Kyle Stanley in bpo-34037.) Added asyncio.PidfdChildWatcher , a Linux-specific child watcher implementation that polls process file descriptors. (bpo-38692) Added a new coroutine asyncio.to_thread() . It is mainly used for running IO-bound functions in a separate thread to avoid blocking the event loop, and essentially works as a high-level version of run_in_executor() that can directly take keyword arguments. (Contributed by Kyle Stanley and Yury Selivanov in bpo-32309.)

compileall¶ Added new possibility to use hardlinks for duplicated .pyc files: hardlink_dupes parameter and –hardlink-dupes command line option. (Contributed by Lumír ‘Frenzy’ Balhar in bpo-40495.) Added new options for path manipulation in resulting .pyc files: stripdir, prependdir, limit_sl_dest parameters and -s, -p, -e command line options. Added the possibility to specify the option for an optimization level multiple times. (Contributed by Lumír ‘Frenzy’ Balhar in bpo-38112.)

concurrent.futures¶ Added a new cancel_futures parameter to concurrent.futures.Executor.shutdown() that cancels all pending futures which have not started running, instead of waiting for them to complete before shutting down the executor. (Contributed by Kyle Stanley in bpo-39349.) Removed daemon threads from ThreadPoolExecutor and ProcessPoolExecutor . This improves compatibility with subinterpreters and predictability in their shutdown processes. (Contributed by Kyle Stanley in bpo-39812.) Workers in ProcessPoolExecutor are now spawned on demand, only when there are no available idle workers to reuse. This optimizes startup overhead and reduces the amount of lost CPU time to idle workers. (Contributed by Kyle Stanley in bpo-39207.)

curses¶ Add curses.get_escdelay() , curses.set_escdelay() , curses.get_tabsize() , and curses.set_tabsize() functions. (Contributed by Anthony Sottile in bpo-38312.)

distutils¶ The upload command now creates SHA2-256 and Blake2b-256 hash digests. It skips MD5 on platforms that block MD5 digest. (Contributed by Christian Heimes in bpo-40698.)

fcntl¶ Added constants F_OFD_GETLK , F_OFD_SETLK and F_OFD_SETLKW . (Contributed by Dong-hee Na in bpo-38602.)

ftplib¶ FTP and FTP_TLS now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Dong-hee Na in bpo-39259.)

gc¶ When the garbage collector makes a collection in which some objects resurrect (they are reachable from outside the isolated cycles after the finalizers have been executed), do not block the collection of all objects that are still unreachable. (Contributed by Pablo Galindo and Tim Peters in bpo-38379.) Added a new function gc.is_finalized() to check if an object has been finalized by the garbage collector. (Contributed by Pablo Galindo in bpo-39322.)

hashlib¶ Builtin hash modules can now be disabled with ./configure --without-builtin-hashlib-hashes or selectively enabled with e.g. ./configure --with-builtin-hashlib-hashes=sha3,blake2 to force use of OpenSSL based implementation. (Contributed by Christian Heimes in bpo-40479)

http¶ HTTP status codes 103 EARLY_HINTS , 418 IM_A_TEAPOT and 425 TOO_EARLY are added to http.HTTPStatus . (Contributed by Dong-hee Na in bpo-39509 and Ross Rhodes in bpo-39507.)

IDLE and idlelib¶ Add option to toggle cursor blink off. (Contributed by Zackery Spytz in bpo-4603.) Escape key now closes IDLE completion windows. (Contributed by Johnny Najera in bpo-38944.) Add keywords to module name completion list. (Contributed by Terry J. Reedy in bpo-37765.) The changes above have been backported to 3.8 maintenance releases.

imaplib¶ IMAP4 and IMAP4_SSL now have an optional timeout parameter for their constructors. Also, the open() method now has an optional timeout parameter with this change. The overridden methods of IMAP4_SSL and IMAP4_stream were applied to this change. (Contributed by Dong-hee Na in bpo-38615.) imaplib.IMAP4.unselect() is added. imaplib.IMAP4.unselect() frees server’s resources associated with the selected mailbox and returns the server to the authenticated state. This command performs the same actions as imaplib.IMAP4.close() , except that no messages are permanently removed from the currently selected mailbox. (Contributed by Dong-hee Na in bpo-40375.)

importlib¶ To improve consistency with import statements, importlib.util.resolve_name() now raises ImportError instead of ValueError for invalid relative import attempts. (Contributed by Ngalim Siregar in bpo-37444.)

inspect¶ inspect.BoundArguments.arguments is changed from OrderedDict to regular dict. (Contributed by Inada Naoki in bpo-36350 and bpo-39775.)

ipaddress¶ ipaddress now supports IPv6 Scoped Addresses (IPv6 address with suffix %<scope_id> ). Scoped IPv6 addresses can be parsed using ipaddress.IPv6Address . If present, scope zone ID is available through the scope_id attribute. (Contributed by Oleksandr Pavliuk in bpo-34788.)

math¶ Expanded the math.gcd() function to handle multiple arguments. Formerly, it only supported two arguments. (Contributed by Serhiy Storchaka in bpo-39648.) Add math.lcm() : return the least common multiple of specified arguments. (Contributed by Mark Dickinson, Ananthakrishnan and Serhiy Storchaka in bpo-39479 and bpo-39648.) Add math.nextafter() : return the next floating-point value after x towards y. (Contributed by Victor Stinner in bpo-39288.) Add math.ulp() : return the value of the least significant bit of a float. (Contributed by Victor Stinner in bpo-39310.)

multiprocessing¶ The multiprocessing.SimpleQueue class has a new close() method to explicitly close the queue. (Contributed by Victor Stinner in bpo-30966.)

nntplib¶ NNTP and NNTP_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Dong-hee Na in bpo-39259.)

os¶ Added CLD_KILLED and CLD_STOPPED for si_code . (Contributed by Dong-hee Na in bpo-38493.) Exposed the Linux-specific os.pidfd_open() (bpo-38692) and os.P_PIDFD (bpo-38713) for process management with file descriptors. The os.unsetenv() function is now also available on Windows. (Contributed by Victor Stinner in bpo-39413.) The os.putenv() and os.unsetenv() functions are now always available. (Contributed by Victor Stinner in bpo-39395.) Add os.waitstatus_to_exitcode() function: convert a wait status to an exit code. (Contributed by Victor Stinner in bpo-40094.)

pathlib¶ Added pathlib.Path.readlink() which acts similarly to os.readlink() . (Contributed by Girts Folkmanis in bpo-30618)

poplib¶ POP3 and POP3_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Dong-hee Na in bpo-39259.)

pprint¶ pprint can now pretty-print types.SimpleNamespace . (Contributed by Carl Bordum Hansen in bpo-37376.)

pydoc¶ The documentation string is now shown not only for class, function, method etc, but for any object that has its own __doc__ attribute. (Contributed by Serhiy Storchaka in bpo-40257.)

random¶ Add a new random.Random.randbytes method: generate random bytes. (Contributed by Victor Stinner in bpo-40286.)

signal¶ Exposed the Linux-specific signal.pidfd_send_signal() for sending to signals to a process using a file descriptor instead of a pid. (bpo-38712)

smtplib¶ SMTP and SMTP_SSL now raise a ValueError if the given timeout for their constructor is zero to prevent the creation of a non-blocking socket. (Contributed by Dong-hee Na in bpo-39259.) LMTP constructor now has an optional timeout parameter. (Contributed by Dong-hee Na in bpo-39329.)

socket¶ The socket module now exports the CAN_RAW_JOIN_FILTERS constant on Linux 4.1 and greater. (Contributed by Stefan Tatschner and Zackery Spytz in bpo-25780.) The socket module now supports the CAN_J1939 protocol on platforms that support it. (Contributed by Karl Ding in bpo-40291.)

time¶ On AIX, thread_time() is now implemented with thread_cputime() which has nanosecond resolution, rather than clock_gettime(CLOCK_THREAD_CPUTIME_ID) which has a resolution of 10 ms. (Contributed by Batuhan Taskaya in bpo-40192)

sys¶ Add a new sys.platlibdir attribute: name of the platform-specific library directory. It is used to build the path of standard library and the paths of installed extension modules. It is equal to "lib" on most platforms. On Fedora and SuSE, it is equal to "lib64" on 64-bit platforms. (Contributed by Jan Matějek, Matěj Cepl, Charalampos Stratakis and Victor Stinner in bpo-1294959.) Previously, sys.stderr was block-buffered when non-interactive. Now stderr defaults to always being line-buffered. (Contributed by Jendrik Seipp in bpo-13601.)

tracemalloc¶ Added tracemalloc.reset_peak() to set the peak size of traced memory blocks to the current size, to measure the peak of specific pieces of code. (Contributed by Huon Wilson in bpo-40630.)

typing¶ PEP 593 introduced an typing.Annotated type to decorate existing types with context-specific metadata and new include_extras parameter to typing.get_type_hints() to access the metadata at runtime. (Contributed by Till Varoquaux and Konstantin Kashin.)

unicodedata¶ The Unicode database has been updated to version 13.0.0. (bpo-39926).

venv¶ The activation scripts provided by venv now all specify their prompt customization consistently by always using the value specified by __VENV_PROMPT__ . Previously some scripts unconditionally used __VENV_PROMPT__ , others only if it happened to be set (which was the default case), and one used __VENV_NAME__ instead. (Contributed by Brett Cannon in bpo-37663.)