What’s New In Python 3.7

Editor:

Elvis Pranskevichus <elvis@magic.io>

This article explains the new features in Python 3.7, compared to 3.6. Python 3.7 was released on June 27, 2018. For full details, see thechangelog.

Summary – Release Highlights

New syntax features:

  • PEP 563,postponed evaluation of type annotations.

Backwards incompatible syntax changes:

New library modules:

New built-in features:

Python data model improvements:

  • PEP 562,customization of access to module attributes.

  • PEP 560,core support for typing module and generic types.

  • the insertion-order preservation nature ofdict objectshas been declaredto be an official part of the Python language spec.

Significant improvements in the standard library:

CPython implementation improvements:

C API improvements:

  • PEP 539,new C API for thread-local storage

Documentation improvements:

This release features notable performance improvements in many areas. TheOptimizationssection lists them in detail.

For a list of changes that may affect compatibility with previous Python releases please refer to thePorting to Python 3.7section.

New Features

PEP 563: Postponed Evaluation of Annotations

The advent of type hints in Python uncovered two glaring usability issues with the functionality of annotations added inPEP 3107and refined further inPEP 526:

  • annotations could only use names which were already available in the current scope, in other words they didn’t support forward references of any kind; and

  • annotating source code had adverse effects on startup time of Python programs.

Both of these issues are fixed by postponing the evaluation of annotations. Instead of compiling code which executes expressions in annotations at their definition time, the compiler stores the annotation in a string form equivalent to the AST of the expression in question. If needed, annotations can be resolved at runtime using typing.get_type_hints().In the common case where this is not required, the annotations are cheaper to store (since short strings are interned by the interpreter) and make startup time faster.

Usability-wise, annotations now support forward references, making the following syntax valid:

classC:
@classmethod
deffrom_string(cls,source:str)->C:
...

defvalidate_b(self,obj:B)->bool:
...

classB:
...

Since this change breaks compatibility, the new behavior needs to be enabled on a per-module basis in Python 3.7 using a__future__import:

from__future__importannotations

It will become the default in Python 3.10.

See also

PEP 563– Postponed evaluation of annotations

PEP written and implemented by Łukasz Langa.

PEP 538: Legacy C Locale Coercion

An ongoing challenge within the Python 3 series has been determining a sensible default strategy for handling the “7-bit ASCII” text encoding assumption currently implied by the use of the default C or POSIX locale on non-Windows platforms.

PEP 538updates the default interpreter command line interface to automatically coerce that locale to an available UTF-8 based locale as described in the documentation of the newPYTHONCOERCECLOCALE environment variable. Automatically settingLC_CTYPEthis way means that both the core interpreter and locale-aware C extensions (such as readline) will assume the use of UTF-8 as the default text encoding, rather than ASCII.

The platform support definition inPEP 11has also been updated to limit full text handling support to suitably configured non-ASCII based locales.

As part of this change, the default error handler forstdinand stdoutis nowsurrogateescape(rather thanstrict) when using any of the defined coercion target locales (currentlyC.UTF-8, C.utf8,andUTF-8). The default error handler forstderr continues to bebackslashreplace,regardless of locale.

Locale coercion is silent by default, but to assist in debugging potentially locale related integration problems, explicit warnings (emitted directly on stderr) can be requested by settingPYTHONCOERCECLOCALE=warn. This setting will also cause the Python runtime to emit a warning if the legacy C locale remains active when the core interpreter is initialized.

WhilePEP 538’s locale coercion has the benefit of also affecting extension modules (such as GNUreadline), as well as child processes (including those running non-Python applications and older versions of Python), it has the downside of requiring that a suitable target locale be present on the running system. To better handle the case where no suitable target locale is available (as occurs on RHEL/CentOS 7, for example), Python 3.7 also implements PEP 540: Forced UTF-8 Runtime Mode.

See also

PEP 538– Coercing the legacy C locale to a UTF-8 based locale

PEP written and implemented by Nick Coghlan.

PEP 540: Forced UTF-8 Runtime Mode

The new-Xutf8command line option andPYTHONUTF8 environment variable can be used to enable thePython UTF-8 Mode.

When in UTF-8 mode, CPython ignores the locale settings, and uses the UTF-8 encoding by default. The error handlers forsys.stdinand sys.stdoutstreams are set tosurrogateescape.

The forced UTF-8 mode can be used to change the text handling behavior in an embedded Python interpreter without changing the locale settings of an embedding application.

WhilePEP 540’s UTF-8 mode has the benefit of working regardless of which locales are available on the running system, it has the downside of having no effect on extension modules (such as GNUreadline), child processes running non-Python applications, and child processes running older versions of Python. To reduce the risk of corrupting text data when communicating with such components, Python 3.7 also implementsPEP 540: Forced UTF-8 Runtime Mode).

The UTF-8 mode is enabled by default when the locale isCorPOSIX,and thePEP 538locale coercion feature fails to change it to a UTF-8 based alternative (whether that failure is due toPYTHONCOERCECLOCALE=0being set, LC_ALLbeing set, or the lack of a suitable target locale).

See also

PEP 540– Add a new UTF-8 mode

PEP written and implemented by Victor Stinner

PEP 553: Built-inbreakpoint()

Python 3.7 includes the new built-inbreakpoint()function as an easy and consistent way to enter the Python debugger.

Built-inbreakpoint()callssys.breakpointhook().By default, the latter importspdband then callspdb.set_trace(),but by binding sys.breakpointhook()to the function of your choosing,breakpoint()can enter any debugger. Additionally, the environment variable PYTHONBREAKPOINTcan be set to the callable of your debugger of choice. SetPYTHONBREAKPOINT=0to completely disable built-in breakpoint().

See also

PEP 553– Built-in breakpoint()

PEP written and implemented by Barry Warsaw

PEP 539: New C API for Thread-Local Storage

While Python provides a C API for thread-local storage support; the existing Thread Local Storage (TLS) APIhas used intto represent TLS keys across all platforms. This has not generally been a problem for officially support platforms, but that is neither POSIX-compliant, nor portable in any practical sense.

PEP 539changes this by providing a newThread Specific Storage (TSS) APIto CPython which supersedes use of the existing TLS API within the CPython interpreter, while deprecating the existing API. The TSS API uses a new typePy_tss_tinstead ofint to represent TSS keys–an opaque type the definition of which may depend on the underlying TLS implementation. Therefore, this will allow to build CPython on platforms where the native TLS key is defined in a way that cannot be safely cast toint.

Note that on platforms where the native TLS key is defined in a way that cannot be safely cast toint,all functions of the existing TLS API will be no-op and immediately return failure. This indicates clearly that the old API is not supported on platforms where it cannot be used reliably, and that no effort will be made to add such support.

See also

PEP 539– A New C-API for Thread-Local Storage in CPython

PEP written by Erik M. Bray; implementation by Masayuki Yamamoto.

PEP 562: Customization of Access to Module Attributes

Python 3.7 allows defining__getattr__()on modules and will call it whenever a module attribute is otherwise not found. Defining __dir__()on modules is now also allowed.

A typical example of where this may be useful is module attribute deprecation and lazy loading.

See also

PEP 562– Module__getattr__and__dir__

PEP written and implemented by Ivan Levkivskyi

PEP 564: New Time Functions With Nanosecond Resolution

The resolution of clocks in modern systems can exceed the limited precision of a floating-point number returned by thetime.time()function and its variants. To avoid loss of precision,PEP 564adds six new “nanosecond” variants of the existing timer functions to thetime module:

The new functions return the number of nanoseconds as an integer value.

Measurements show that on Linux and Windows the resolution oftime.time_ns()is approximately 3 times better than that oftime.time().

See also

PEP 564– Add new time functions with nanosecond resolution

PEP written and implemented by Victor Stinner

PEP 565: Show DeprecationWarning in__main__

The default handling ofDeprecationWarninghas been changed such that these warnings are once more shown by default, but only when the code triggering them is running directly in the__main__module. As a result, developers of single file scripts and those using Python interactively should once again start seeing deprecation warnings for the APIs they use, but deprecation warnings triggered by imported application, library and framework modules will continue to be hidden by default.

As a result of this change, the standard library now allows developers to choose between three different deprecation warning behaviours:

  • FutureWarning:always displayed by default, recommended for warnings intended to be seen by application end users (e.g. for deprecated application configuration settings).

  • DeprecationWarning:displayed by default only in__main__and when running tests, recommended for warnings intended to be seen by other Python developers where a version upgrade may result in changed behaviour or an error.

  • PendingDeprecationWarning:displayed by default only when running tests, intended for cases where a future version upgrade will change the warning category toDeprecationWarningorFutureWarning.

Previously bothDeprecationWarningandPendingDeprecationWarning were only visible when running tests, which meant that developers primarily writing single file scripts or using Python interactively could be surprised by breaking changes in the APIs they used.

See also

PEP 565– Show DeprecationWarning in__main__

PEP written and implemented by Nick Coghlan

PEP 560: Core Support fortypingmodule and Generic Types

InitiallyPEP 484was designed in such way that it would not introduceany changes to the core CPython interpreter. Now type hints and thetyping module are extensively used by the community, so this restriction is removed. The PEP introduces two special methods__class_getitem__()and __mro_entries__,these methods are now used by most classes and special constructs intyping.As a result, the speed of various operations with types increased up to 7 times, the generic types can be used without metaclass conflicts, and several long standing bugs intypingmodule are fixed.

See also

PEP 560– Core support for typing module and generic types

PEP written and implemented by Ivan Levkivskyi

PEP 552: Hash-based.pyc Files

Python has traditionally checked the up-to-dateness of bytecode cache files (i.e.,.pycfiles) by comparing the source metadata (last-modified timestamp and size) with source metadata saved in the cache file header when it was generated. While effective, this invalidation method has its drawbacks. When filesystem timestamps are too coarse, Python can miss source updates, leading to user confusion. Additionally, having a timestamp in the cache file is problematic forbuild reproducibilityand content-based build systems.

PEP 552extends the pyc format to allow the hash of the source file to be used for invalidation instead of the source timestamp. Such.pycfiles are called “hash-based”. By default, Python still uses timestamp-based invalidation and does not generate hash-based.pycfiles at runtime. Hash-based.pyc files may be generated withpy_compileorcompileall.

Hash-based.pycfiles come in two variants: checked and unchecked. Python validates checked hash-based.pycfiles against the corresponding source files at runtime but doesn’t do so for unchecked hash-based pycs. Unchecked hash-based.pycfiles are a useful performance optimization for environments where a system external to Python (e.g., the build system) is responsible for keeping.pycfiles up-to-date.

SeeCached bytecode invalidationfor more information.

See also

PEP 552– Deterministic pycs

PEP written and implemented by Benjamin Peterson

PEP 545: Python Documentation Translations

PEP 545describes the process of creating and maintaining Python documentation translations.

Three new translations have been added:

See also

PEP 545– Python Documentation Translations

PEP written and implemented by Julien Palard, Inada Naoki, and Victor Stinner.

Python Development Mode (-X dev)

The new-Xdevcommand line option or the new PYTHONDEVMODEenvironment variable can be used to enable Python Development Mode.When in development mode, Python performs additional runtime checks that are too expensive to be enabled by default. SeePython Development Modedocumentation for the full description.

Other Language Changes

  • Anawaitexpression and comprehensions containing an asyncforclause were illegal in the expressions in formatted string literalsdue to a problem with the implementation. In Python 3.7 this restriction was lifted.

  • More than 255 arguments can now be passed to a function, and a function can now have more than 255 parameters. (Contributed by Serhiy Storchaka in bpo-12844andbpo-18896.)

  • bytes.fromhex()andbytearray.fromhex()now ignore all ASCII whitespace, not only spaces. (Contributed by Robert Xiao inbpo-28927.)

  • str,bytes,andbytearraygained support for the newisascii()method, which can be used to test if a string or bytes contain only the ASCII characters. (Contributed by INADA Naoki inbpo-32677.)

  • ImportErrornow displays module name and module__file__path when from...import...fails. (Contributed by Matthias Bussonnier in bpo-29546.)

  • Circular imports involving absolute imports with binding a submodule to a name are now supported. (Contributed by Serhiy Storchaka inbpo-30024.)

  • object.__format__(x,'')is now equivalent tostr(x)rather than format(str(self),''). (Contributed by Serhiy Storchaka inbpo-28974.)

  • In order to better support dynamic creation of stack traces, types.TracebackTypecan now be instantiated from Python code, and thetb_nextattribute on tracebacksis now writable. (Contributed by Nathaniel J. Smith inbpo-30579.)

  • When using the-mswitch,sys.path[0]is now eagerly expanded to the full starting directory path, rather than being left as the empty directory (which allows imports from thecurrentworking directory at the time when an import occurs) (Contributed by Nick Coghlan inbpo-33053.)

  • The new-Ximporttimeoption or the PYTHONPROFILEIMPORTTIMEenvironment variable can be used to show the timing of each module import. (Contributed by Inada Naoki inbpo-31415.)

New Modules

contextvars

The newcontextvarsmodule and a set of new C APIsintroduce support forcontext variables.Context variables are conceptually similar to thread-local variables. Unlike TLS, context variables support asynchronous code correctly.

Theasyncioanddecimalmodules have been updated to use and support context variables out of the box. Particularly the active decimal context is now stored in a context variable, which allows decimal operations to work with the correct context in asynchronous code.

See also

PEP 567– Context Variables

PEP written and implemented by Yury Selivanov

dataclasses

The newdataclass()decorator provides a way to declare data classes.A data class describes its attributes using class variable annotations. Its constructor and other magic methods, such as __repr__(),__eq__(),and __hash__()are generated automatically.

Example:

@dataclass
classPoint:
x:float
y:float
z:float=0.0

p=Point(1.5,2.5)
print(p)# produces "Point(x=1.5, y=2.5, z=0.0)"

See also

PEP 557– Data Classes

PEP written and implemented by Eric V. Smith

importlib.resources

The newimportlib.resourcesmodule provides several new APIs and one new ABC for access to, opening, and readingresourcesinside packages. Resources are roughly similar to files inside packages, but they needn’t be actual files on the physical file system. Module loaders can provide a get_resource_reader()function which returns aimportlib.abc.ResourceReaderinstance to support this new API. Built-in file path loaders and zip file loaders both support this.

Contributed by Barry Warsaw and Brett Cannon inbpo-32248.

See also

importlib_resources – a PyPI backport for earlier Python versions.

Improved Modules

argparse

The newArgumentParser.parse_intermixed_args() method allows intermixing options and positional arguments. (Contributed by paul.j3 inbpo-14191.)

asyncio

Theasynciomodule has received many new features, usability and performance improvements.Notable changes include:

SeveralasyncioAPIs have been deprecated.

binascii

Theb2a_uu()function now accepts an optionalbacktick keyword argument. When it’s true, zeros are represented by'`' instead of spaces. (Contributed by Xiang Zhang inbpo-30103.)

calendar

TheHTMLCalendarclass has new class attributes which ease the customization of CSS classes in the produced HTML calendar. (Contributed by Oz Tiram inbpo-30095.)

collections

collections.namedtuple()now supports default values. (Contributed by Raymond Hettinger inbpo-32320.)

compileall

compileall.compile_dir()learned the newinvalidation_modeparameter, which can be used to enable hash-based.pyc invalidation.The invalidation mode can also be specified on the command line using the new --invalidation-modeargument. (Contributed by Benjamin Peterson inbpo-31650.)

concurrent.futures

ProcessPoolExecutorand ThreadPoolExecutornow support the newinitializerandinitargsconstructor arguments. (Contributed by Antoine Pitrou inbpo-21423.)

TheProcessPoolExecutor can now take the multiprocessing context via the newmp_contextargument. (Contributed by Thomas Moreau inbpo-31540.)

contextlib

The newnullcontext()is a simpler and faster no-op context manager thanExitStack. (Contributed by Jesse-Bakker inbpo-10049.)

The newasynccontextmanager(), AbstractAsyncContextManager,and AsyncExitStackhave been added to complement their synchronous counterparts. (Contributed by Jelle Zijlstra inbpo-29679andbpo-30241, and by Alexander Mohr and Ilya Kulakov inbpo-29302.)

cProfile

ThecProfilecommand line now accepts-mmodule_nameas an alternative to script path. (Contributed by Sanyam Khurana inbpo-21862.)

crypt

Thecryptmodule now supports the Blowfish hashing method. (Contributed by Serhiy Storchaka inbpo-31664.)

Themksalt()function now allows specifying the number of rounds for hashing. (Contributed by Serhiy Storchaka inbpo-31702.)

datetime

The newdatetime.fromisoformat() method constructs adatetimeobject from a string in one of the formats output by datetime.isoformat(). (Contributed by Paul Ganssle inbpo-15873.)

Thetzinfoclass now supports sub-minute offsets. (Contributed by Alexander Belopolsky inbpo-5288.)

dbm

dbm.dumbnow supports reading read-only files and no longer writes the index file when it is not changed.

decimal

Thedecimalmodule now usescontext variables to store the decimal context. (Contributed by Yury Selivanov inbpo-32630.)

dis

Thedis()function is now able to disassemble nested code objects (the code of comprehensions, generator expressions and nested functions, and the code used for building nested classes). The maximum depth of disassembly recursion is controlled by the newdepthparameter. (Contributed by Serhiy Storchaka inbpo-11822.)

distutils

README.rstis now included in the list of distutils standard READMEs and therefore included in source distributions. (Contributed by Ryan Gonzalez inbpo-11913.)

enum

TheEnumlearned the new_ignore_class property, which allows listing the names of properties which should not become enum members. (Contributed by Ethan Furman inbpo-31801.)

In Python 3.8, attempting to check for non-Enum objects inEnum classes will raise aTypeError(e.g.1inColor); similarly, attempting to check for non-Flag objects in aFlagmember will raiseTypeError(e.g.1inPerm.RW); currently, both operations returnFalseinstead and are deprecated. (Contributed by Ethan Furman inbpo-33217.)

functools

functools.singledispatch()now supports registering implementations using type annotations. (Contributed by Łukasz Langa inbpo-32227.)

gc

The newgc.freeze()function allows freezing all objects tracked by the garbage collector and excluding them from future collections. This can be used before a POSIXfork()call to make the GC copy-on-write friendly or to speed up collection. The newgc.unfreeze()functions reverses this operation. Additionally,gc.get_freeze_count()can be used to obtain the number of frozen objects. (Contributed by Li Zekun inbpo-31558.)

hmac

Thehmacmodule now has an optimized one-shotdigest() function, which is up to three times faster thanHMAC(). (Contributed by Christian Heimes inbpo-32433.)

http.client

HTTPConnectionandHTTPSConnection now support the newblocksizeargument for improved upload throughput. (Contributed by Nir Soffer inbpo-31945.)

http.server

SimpleHTTPRequestHandlernow supports the HTTP If-Modified-Sinceheader. The server returns the 304 response status if the target file was not modified after the time specified in the header. (Contributed by Pierre Quentel inbpo-29654.)

SimpleHTTPRequestHandleraccepts the newdirectory argument, in addition to the new--directorycommand line argument. With this parameter, the server serves the specified directory, by default it uses the current working directory. (Contributed by Stéphane Wirtel and Julien Palard inbpo-28707.)

The newThreadingHTTPServerclass uses threads to handle requests usingThreadingMixin. It is used whenhttp.serveris run with-m. (Contributed by Julien Palard inbpo-31639.)

idlelib and IDLE

Multiple fixes for autocompletion. (Contributed by Louie Lu inbpo-15786.)

Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy inbpo-1612262.)

The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)

The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy inbpo-13802.) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka inbpo-31860.)

The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy inbpo-27099.)

Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy inbpo-33642, bpo-33768,andbpo-33679.)

On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy inbpo-33656.)

New in 3.7.1:

Output over N lines (50 by default) is squeezed down to a button. N can be changed in the PyShell section of the General page of the Settings dialog. Fewer, but possibly extra long, lines can be squeezed by right clicking on the output. Squeezed output can be expanded in place by double-clicking the button or into the clipboard or a separate window by right-clicking the button. (Contributed by Tal Einat inbpo-1529353.)

The changes above have been backported to 3.6 maintenance releases.

NEW in 3.7.4:

Add “Run Customized” to the Run menu to run a module with customized settings. Any command line arguments entered are added to sys.argv. They re-appear in the box for the next customized run. One can also suppress the normal Shell main module restart. (Contributed by Cheryl Sabella, Terry Jan Reedy, and others inbpo-5680andbpo-37627.)

New in 3.7.5:

Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar inbpo-17535.)

importlib

Theimportlib.abc.ResourceReaderABC was introduced to support the loading of resources from packages. See also importlib.resources. (Contributed by Barry Warsaw, Brett Cannon inbpo-32248.)

importlib.reload()now raisesModuleNotFoundErrorif the module lacks a spec. (Contributed by Garvit Khatri inbpo-29851.)

importlib.find_spec()now raisesModuleNotFoundErrorinstead of AttributeErrorif the specified parent module is not a package (i.e. lacks a__path__attribute). (Contributed by Milan Oberkirch inbpo-30436.)

The newimportlib.source_hash()can be used to compute the hash of the passed source. Ahash-based.pyc file embeds the value returned by this function.

io

The newTextIOWrapper.reconfigure() method can be used to reconfigure the text stream with the new settings. (Contributed by Antoine Pitrou inbpo-30526and INADA Naoki inbpo-15216.)

ipaddress

The newsubnet_of()andsupernet_of()methods of ipaddress.IPv6Networkandipaddress.IPv4Networkcan be used for network containment tests. (Contributed by Michel Albert and Cheryl Sabella inbpo-20825.)

itertools

itertools.islice()now accepts integer-likeobjectsas start, stop, and slice arguments. (Contributed by Will Roberts inbpo-30537.)

locale

The newmonetaryargument tolocale.format_string()can be used to make the conversion use monetary thousands separators and grouping strings. (Contributed by Garvit inbpo-10379.)

Thelocale.getpreferredencoding()function now always returns'UTF-8' on Android or when in theforced UTF-8 mode.

logging

Loggerinstances can now be pickled. (Contributed by Vinay Sajip inbpo-30520.)

The newStreamHandler.setStream() method can be used to replace the logger stream after handler creation. (Contributed by Vinay Sajip inbpo-30522.)

It is now possible to specify keyword arguments to handler constructors in configuration passed tologging.config.fileConfig(). (Contributed by Preston Landers inbpo-31080.)

math

The newmath.remainder()function implements the IEEE 754-style remainder operation. (Contributed by Mark Dickinson inbpo-29962.)

mimetypes

The MIME type of.bmp has been changed from'image/x-ms-bmp'to 'image/bmp'. (Contributed by Nitish Chandra inbpo-22589.)

msilib

The newDatabase.Close()method can be used to close theMSIdatabase. (Contributed by Berker Peksag inbpo-20486.)

multiprocessing

The newProcess.close()method explicitly closes the process object and releases all resources associated with it.ValueErroris raised if the underlying process is still running. (Contributed by Antoine Pitrou inbpo-30596.)

The newProcess.kill()method can be used to terminate the process using theSIGKILLsignal on Unix. (Contributed by Vitor Pereira inbpo-30794.)

Non-daemonic threads created byProcessare now joined on process exit. (Contributed by Antoine Pitrou inbpo-18966.)

os

os.fwalk()now accepts thepathargument asbytes. (Contributed by Serhiy Storchaka inbpo-28682.)

os.scandir()gained support forfile descriptors. (Contributed by Serhiy Storchaka inbpo-25996.)

The newregister_at_fork()function allows registering Python callbacks to be executed at process fork. (Contributed by Antoine Pitrou inbpo-16500.)

Addedos.preadv()(combine the functionality ofos.readv()and os.pread()) andos.pwritev()functions (combine the functionality ofos.writev()andos.pwrite()). (Contributed by Pablo Galindo in bpo-31368.)

The mode argument ofos.makedirs()no longer affects the file permission bits of newly created intermediate-level directories. (Contributed by Serhiy Storchaka inbpo-19930.)

os.dup2()now returns the new file descriptor. Previously,None was always returned. (Contributed by Benjamin Peterson inbpo-32441.)

The structure returned byos.stat()now contains the st_fstypeattribute on Solaris and its derivatives. (Contributed by Jesús Cea Avión inbpo-32659.)

pathlib

The newPath.is_mount()method is now available on POSIX systems and can be used to determine whether a path is a mount point. (Contributed by Cooper Ry Lees inbpo-30897.)

pdb

pdb.set_trace()now takes an optionalheaderkeyword-only argument. If given, it is printed to the console just before debugging begins. (Contributed by Barry Warsaw inbpo-31389.)

pdbcommand line now accepts-mmodule_nameas an alternative to script file. (Contributed by Mario Corchero inbpo-32206.)

py_compile

py_compile.compile()– and by extension,compileall– now respects theSOURCE_DATE_EPOCHenvironment variable by unconditionally creating.pycfiles for hash-based validation. This allows for guaranteeing reproducible buildsof.pyc files when they are created eagerly. (Contributed by Bernhard M. Wiedemann inbpo-29708.)

pydoc

The pydoc server can now bind to an arbitrary hostname specified by the new-ncommand-line argument. (Contributed by Feanil Patel inbpo-31128.)

queue

The newSimpleQueueclass is an unboundedFIFOqueue. (Contributed by Antoine Pitrou inbpo-14976.)

re

The flagsre.ASCII,re.LOCALEandre.UNICODE can be set within the scope of a group. (Contributed by Serhiy Storchaka inbpo-31690.)

re.split()now supports splitting on a pattern liker'\b', '^$'or(?=-)that matches an empty string. (Contributed by Serhiy Storchaka inbpo-25054.)

Regular expressions compiled with there.LOCALEflag no longer depend on the locale at compile time. Locale settings are applied only when the compiled regular expression is used. (Contributed by Serhiy Storchaka inbpo-30215.)

FutureWarningis now emitted if a regular expression contains character set constructs that will change semantically in the future, such as nested sets and set operations. (Contributed by Serhiy Storchaka inbpo-30349.)

Compiled regular expression and match objects can now be copied usingcopy.copy()andcopy.deepcopy(). (Contributed by Serhiy Storchaka inbpo-10076.)

signal

The newwarn_on_full_bufferargument to thesignal.set_wakeup_fd() function makes it possible to specify whether Python prints a warning on stderr when the wakeup buffer overflows. (Contributed by Nathaniel J. Smith inbpo-30050.)

socket

The newsocket.getblocking()method returnsTrueif the socket is in blocking mode andFalseotherwise. (Contributed by Yury Selivanov inbpo-32373.)

The newsocket.close()function closes the passed socket file descriptor. This function should be used instead ofos.close()for better compatibility across platforms. (Contributed by Christian Heimes inbpo-32454.)

Thesocketmodule now exposes thesocket.TCP_CONGESTION (Linux 2.6.13),socket.TCP_USER_TIMEOUT(Linux 2.6.37), and socket.TCP_NOTSENT_LOWAT(Linux 3.12) constants. (Contributed by Omar Sandoval inbpo-26273and Nathaniel J. Smith inbpo-29728.)

Support forsocket.AF_VSOCKsockets has been added to allow communication between virtual machines and their hosts. (Contributed by Cathy Avery inbpo-27584.)

Sockets now auto-detect family, type and protocol from file descriptor by default. (Contributed by Christian Heimes inbpo-28134.)

socketserver

socketserver.ThreadingMixIn.server_close()now waits until all non-daemon threads complete.socketserver.ForkingMixIn.server_close()now waits until all child processes complete.

Add a newsocketserver.ForkingMixIn.block_on_closeclass attribute to socketserver.ForkingMixInandsocketserver.ThreadingMixIn classes. Set the class attribute toFalseto get the pre-3.7 behaviour.

sqlite3

sqlite3.Connectionnow exposes thebackup() method when the underlying SQLite library is at version 3.6.11 or higher. (Contributed by Lele Gaifax inbpo-27645.)

Thedatabaseargument ofsqlite3.connect()now accepts any path-like object,instead of just a string. (Contributed by Anders Lorentsen inbpo-31843.)

ssl

Thesslmodule now uses OpenSSL’s builtin API instead of match_hostname()to check a host name or an IP address. Values are validated during TLS handshake. Any certificate validation error including failing the host name check now raises SSLCertVerificationErrorand aborts the handshake with a proper TLS Alert message. The new exception contains additional information. Host name validation can be customized with SSLContext.hostname_checks_common_name. (Contributed by Christian Heimes inbpo-31399.)

Note

The improved host name check requires alibsslimplementation compatible with OpenSSL 1.0.2 or 1.1. Consequently, OpenSSL 0.9.8 and 1.0.1 are no longer supported (seePlatform Support Removalsfor more details). The ssl module is mostly compatible with LibreSSL 2.7.2 and newer.

Thesslmodule no longer sends IP addresses in SNI TLS extension. (Contributed by Christian Heimes inbpo-32185.)

match_hostname()no longer supports partial wildcards like www*.example.org. (Contributed by Mandeep Singh inbpo-23033and Christian Heimes in bpo-31399.)

The default cipher suite selection of thesslmodule now uses a blacklist approach rather than a hard-coded whitelist. Python no longer re-enables ciphers that have been blocked by OpenSSL security updates. Default cipher suite selection can be configured at compile time. (Contributed by Christian Heimes inbpo-31429.)

Validation of server certificates containing internationalized domain names (IDNs) is now supported. As part of this change, the SSLSocket.server_hostnameattribute now stores the expected hostname in A-label form ("xn--pythn-mua.org"), rather than the U-label form ("pythön.org"). (Contributed by Nathaniel J. Smith and Christian Heimes inbpo-28414.)

Thesslmodule has preliminary and experimental support for TLS 1.3 and OpenSSL 1.1.1. At the time of Python 3.7.0 release, OpenSSL 1.1.1 is still under development and TLS 1.3 hasn’t been finalized yet. The TLS 1.3 handshake and protocol behaves slightly differently than TLS 1.2 and earlier, seeTLS 1.3. (Contributed by Christian Heimes inbpo-32947,bpo-20995, bpo-29136,bpo-30622andbpo-33618)

SSLSocketandSSLObjectno longer have a public constructor. Direct instantiation was never a documented and supported feature. Instances must be created withSSLContextmethods wrap_socket()andwrap_bio(). (Contributed by Christian Heimes inbpo-32951)

OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are available asSSLContext.minimum_version andSSLContext.maximum_version. Supported protocols are indicated by several new flags, such as HAS_TLSv1_1. (Contributed by Christian Heimes inbpo-32609.)

Addedssl.SSLContext.post_handshake_authto enable and ssl.SSLSocket.verify_client_post_handshake()to initiate TLS 1.3 post-handshake authentication. (Contributed by Christian Heimes ingh-78851.)

string

string.Templatenow lets you to optionally modify the regular expression pattern for braced placeholders and non-braced placeholders separately. (Contributed by Barry Warsaw inbpo-1198569.)

subprocess

Thesubprocess.run()function accepts the newcapture_output keyword argument. When true, stdout and stderr will be captured. This is equivalent to passingsubprocess.PIPEasstdoutand stderrarguments. (Contributed by Bo Bayles inbpo-32102.)

Thesubprocess.runfunction and thesubprocess.Popenconstructor now accept thetextkeyword argument as an alias touniversal_newlines. (Contributed by Andrew Clegg inbpo-31756.)

On Windows the default forclose_fdswas changed fromFalseto Truewhen redirecting the standard handles. It’s now possible to set close_fdsto true when redirecting the standard handles. See subprocess.Popen.This means thatclose_fdsnow defaults to Trueon all supported platforms. (Contributed by Segev Finer inbpo-19764.)

The subprocess module is now more graceful when handling KeyboardInterruptduringsubprocess.call(), subprocess.run(),or in aPopen context manager. It now waits a short amount of time for the child to exit, before continuing the handling of theKeyboardInterrupt exception. (Contributed by Gregory P. Smith inbpo-25942.)

sys

The newsys.breakpointhook()hook function is called by the built-inbreakpoint(). (Contributed by Barry Warsaw inbpo-31353.)

On Android, the newsys.getandroidapilevel()returns the build-time Android API version. (Contributed by Victor Stinner inbpo-28740.)

The newsys.get_coroutine_origin_tracking_depth()function returns the current coroutine origin tracking depth, as set by the newsys.set_coroutine_origin_tracking_depth().asyncio has been converted to use this new API instead of the deprecatedsys.set_coroutine_wrapper(). (Contributed by Nathaniel J. Smith inbpo-32591.)

time

PEP 564adds six new functions with nanosecond resolution to the timemodule:

New clock identifiers have been added:

  • time.CLOCK_BOOTTIME(Linux): Identical to time.CLOCK_MONOTONIC,except it also includes any time that the system is suspended.

  • time.CLOCK_PROF(FreeBSD, NetBSD and OpenBSD): High-resolution per-process CPU timer.

  • time.CLOCK_UPTIME(FreeBSD, OpenBSD): Time whose absolute value is the time the system has been running and not suspended, providing accurate uptime measurement.

The newtime.thread_time()andtime.thread_time_ns()functions can be used to get per-thread CPU time measurements. (Contributed by Antoine Pitrou inbpo-32025.)

The newtime.pthread_getcpuclockid()function returns the clock ID of the thread-specific CPU-time clock.

tkinter

The newtkinter.ttk.Spinboxclass is now available. (Contributed by Alan Moore inbpo-32585.)

tracemalloc

tracemalloc.Tracebackbehaves more like regular tracebacks, sorting the frames from oldest to most recent. Traceback.format() now accepts negativelimit,truncating the result to the abs(limit)oldest frames. To get the old behaviour, use the newmost_recent_firstargument toTraceback.format(). (Contributed by Jesse Bakker inbpo-32121.)

types

The newWrapperDescriptorType, MethodWrapperType,MethodDescriptorType, andClassMethodDescriptorTypeclasses are now available. (Contributed by Manuel Krebber and Guido van Rossum inbpo-29377, and Serhiy Storchaka inbpo-32265.)

The newtypes.resolve_bases()function resolves MRO entries dynamically as specified byPEP 560. (Contributed by Ivan Levkivskyi inbpo-32717.)

unicodedata

The internalunicodedatadatabase has been upgraded to useUnicode 11.(Contributed by Benjamin Peterson.)

unittest

The new-kcommand-line option allows filtering tests by a name substring or a Unix shell-like pattern. For example,python-munittest-kfooruns foo_tests.SomeTest.test_something,bar_tests.SomeTest.test_foo, but notbar_tests.FooTest.test_something. (Contributed by Jonas Haag inbpo-32071.)

unittest.mock

Thesentinelattributes now preserve their identity when they arecopiedorpickled.(Contributed by Serhiy Storchaka inbpo-20804.)

The newseal()function allows sealing Mockinstances, which will disallow further creation of attribute mocks. The seal is applied recursively to all attributes that are themselves mocks. (Contributed by Mario Corchero inbpo-30541.)

urllib.parse

urllib.parse.quote()has been updated fromRFC 2396toRFC 3986, adding~to the set of characters that are never quoted by default. (Contributed by Christian Theune and Ratnadeep Debnath inbpo-16285.)

uu

Theuu.encode()function now accepts an optionalbacktick keyword argument. When it’s true, zeros are represented by'`' instead of spaces. (Contributed by Xiang Zhang inbpo-30103.)

uuid

The newUUID.is_safeattribute relays information from the platform about whether generated UUIDs are generated with a multiprocessing-safe method. (Contributed by Barry Warsaw inbpo-22807.)

uuid.getnode()now prefers universally administered MAC addresses over locally administered MAC addresses. This makes a better guarantee for global uniqueness of UUIDs returned fromuuid.uuid1().If only locally administered MAC addresses are available, the first such one found is returned. (Contributed by Barry Warsaw inbpo-32107.)

warnings

The initialization of the default warnings filters has changed as follows:

  • warnings enabled via command line options (including those for-b and the new CPython-specific-Xdevoption) are always passed to the warnings machinery via thesys.warnoptionsattribute.

  • warnings filters enabled via the command line or the environment now have the following order of precedence:

    • theBytesWarningfilter for-b(or-bb)

    • any filters specified with the-Woption

    • any filters specified with thePYTHONWARNINGSenvironment variable

    • any other CPython specific filters (e.g. thedefaultfilter added for the new-Xdevmode)

    • any implicit filters defined directly by the warnings machinery

  • inCPython debug builds,all warnings are now displayed by default (the implicit filter list is empty)

(Contributed by Nick Coghlan and Victor Stinner inbpo-20361, bpo-32043,andbpo-32230.)

Deprecation warnings are once again shown by default in single-file scripts and at the interactive prompt. SeePEP 565: Show DeprecationWarning in __main__for details. (Contributed by Nick Coghlan inbpo-31975.)

xml

As mitigation against DTD and external entity retrieval, the xml.dom.minidomandxml.saxmodules no longer process external entities by default. (Contributed by Christian Heimes ingh-61441.)

xml.etree

ElementPathpredicates in thefind() methods can now compare text of the current node with[.="text" ], not only text in children. Predicates also allow adding spaces for better readability. (Contributed by Stefan Behnel inbpo-31648.)

xmlrpc.server

SimpleXMLRPCDispatcher.register_function can now be used as a decorator. (Contributed by Xiang Zhang in bpo-7769.)

zipapp

Functioncreate_archive()now accepts an optionalfilter argument to allow the user to select which files should be included in the archive. (Contributed by Irmen de Jong inbpo-31072.)

Functioncreate_archive()now accepts an optionalcompressed argument to generate a compressed archive. A command line option --compresshas also been added to support compression. (Contributed by Zhiming Wang inbpo-31638.)

zipfile

ZipFilenow accepts the newcompresslevelparameter to control the compression level. (Contributed by Bo Bayles inbpo-21417.)

Subdirectories in archives created byZipFileare now stored in alphabetical order. (Contributed by Bernhard M. Wiedemann inbpo-30693.)

C API Changes

A new API for thread-local storage has been implemented. See PEP 539: New C API for Thread-Local Storagefor an overview and Thread Specific Storage (TSS) APIfor a complete reference. (Contributed by Masayuki Yamamoto inbpo-25658.)

The newcontext variablesfunctionality exposes a number ofnew C APIs.

The newPyImport_GetModule()function returns the previously imported module with the given name. (Contributed by Eric Snow inbpo-28411.)

The newPy_RETURN_RICHCOMPAREmacro eases writing rich comparison functions. (Contributed by Petr Victorin inbpo-23699.)

The newPy_UNREACHABLEmacro can be used to mark unreachable code paths. (Contributed by Barry Warsaw inbpo-31338.)

Thetracemallocnow exposes a C API through the new PyTraceMalloc_Track()andPyTraceMalloc_Untrack() functions. (Contributed by Victor Stinner inbpo-30054.)

The newimport__find__load__start()and import__find__load__done()static markers can be used to trace module imports. (Contributed by Christian Heimes inbpo-31574.)

The fieldsnameanddocof structures PyMemberDef,PyGetSetDef, PyStructSequence_Field,PyStructSequence_Desc, andwrapperbaseare now of typeconstchar*rather of char*.(Contributed by Serhiy Storchaka inbpo-28761.)

The result ofPyUnicode_AsUTF8AndSize()andPyUnicode_AsUTF8() is now of typeconstchar*rather ofchar*.(Contributed by Serhiy Storchaka inbpo-28769.)

The result ofPyMapping_Keys(),PyMapping_Values()and PyMapping_Items()is now always a list, rather than a list or a tuple. (Contributed by Oren Milman inbpo-28280.)

Added functionsPySlice_Unpack()andPySlice_AdjustIndices(). (Contributed by Serhiy Storchaka inbpo-27867.)

PyOS_AfterFork()is deprecated in favour of the new functions PyOS_BeforeFork(),PyOS_AfterFork_Parent()and PyOS_AfterFork_Child().(Contributed by Antoine Pitrou in bpo-16500.)

ThePyExc_RecursionErrorInstsingleton that was part of the public API has been removed as its members being never cleared may cause a segfault during finalization of the interpreter. Contributed by Xavier de Gaye in bpo-22898andbpo-30697.

Added C API support for timezones with timezone constructors PyTimeZone_FromOffset()andPyTimeZone_FromOffsetAndName(), and access to the UTC singleton withPyDateTime_TimeZone_UTC. Contributed by Paul Ganssle inbpo-10381.

The type of results ofPyThread_start_new_thread()and PyThread_get_thread_ident(),and theidparameter of PyThreadState_SetAsyncExc()changed fromlongto unsignedlong. (Contributed by Serhiy Storchaka inbpo-6532.)

PyUnicode_AsWideCharString()now raises aValueErrorif the second argument isNULLand thewchar_t*string contains null characters. (Contributed by Serhiy Storchaka inbpo-30708.)

Changes to the startup sequence and the management of dynamic memory allocators mean that the long documented requirement to call Py_Initialize()before calling most C API functions is now relied on more heavily, and failing to abide by it may lead to segfaults in embedding applications. See thePorting to Python 3.7section in this document and theBefore Python Initializationsection in the C API documentation for more details.

The newPyInterpreterState_GetID()returns the unique ID for a given interpreter. (Contributed by Eric Snow inbpo-29102.)

Py_DecodeLocale(),Py_EncodeLocale()now use the UTF-8 encoding when theUTF-8 modeis enabled. (Contributed by Victor Stinner inbpo-29240.)

PyUnicode_DecodeLocaleAndSize()andPyUnicode_EncodeLocale() now use the current locale encoding forsurrogateescapeerror handler. (Contributed by Victor Stinner inbpo-29240.)

Thestartandendparameters ofPyUnicode_FindChar()are now adjusted to behave like string slices. (Contributed by Xiang Zhang inbpo-28822.)

Build Changes

Support for building--without-threadshas been removed. The threadingmodule is now always available. (Contributed by Antoine Pitrou inbpo-31370.).

A full copy of libffi is no longer bundled for use when building the _ctypesmodule on non-OSX UNIX platforms. An installed copy of libffi is now required when building_ctypeson such platforms. (Contributed by Zachary Ware inbpo-27979.)

The Windows build process no longer depends on Subversion to pull in external sources, a Python script is used to download zipfiles from GitHub instead. If Python 3.6 is not found on the system (viapy-3.6), NuGet is used to download a copy of 32-bit Python for this purpose. (Contributed by Zachary Ware inbpo-30450.)

Thesslmodule requires OpenSSL 1.0.2 or 1.1 compatible libssl. OpenSSL 1.0.1 has reached end of lifetime on 2016-12-31 and is no longer supported. LibreSSL is temporarily not supported as well. LibreSSL releases up to version 2.6.4 are missing required OpenSSL 1.0.2 APIs.

Optimizations

The overhead of calling many methods of various standard library classes implemented in C has been significantly reduced by porting more code to use theMETH_FASTCALLconvention. (Contributed by Victor Stinner inbpo-29300,bpo-29507, bpo-29452,andbpo-29286.)

Various optimizations have reduced Python startup time by 10% on Linux and up to 30% on macOS. (Contributed by Victor Stinner, INADA Naoki inbpo-29585,and Ivan Levkivskyi inbpo-31333.)

Method calls are now up to 20% faster due to the bytecode changes which avoid creating bound method instances. (Contributed by Yury Selivanov and INADA Naoki inbpo-26110.)

Theasynciomodule received a number of notable optimizations for commonly used functions:

  • Theasyncio.get_event_loop()function has been reimplemented in C to make it up to 15 times faster. (Contributed by Yury Selivanov inbpo-32296.)

  • asyncio.Futurecallback management has been optimized. (Contributed by Yury Selivanov inbpo-32348.)

  • asyncio.gather()is now up to 15% faster. (Contributed by Yury Selivanov inbpo-32355.)

  • asyncio.sleep()is now up to 2 times faster when thedelay argument is zero or negative. (Contributed by Andrew Svetlov inbpo-32351.)

  • The performance overhead of asyncio debug mode has been reduced. (Contributed by Antoine Pitrou inbpo-31970.)

As a result ofPEP 560 work,the import time oftypinghas been reduced by a factor of 7, and many typing operations are now faster. (Contributed by Ivan Levkivskyi inbpo-32226.)

sorted()andlist.sort()have been optimized for common cases to be up to 40-75% faster. (Contributed by Elliot Gorokhovsky inbpo-28685.)

dict.copy()is now up to 5.5 times faster. (Contributed by Yury Selivanov inbpo-31179.)

hasattr()andgetattr()are now about 4 times faster when nameis not found andobjdoes not overrideobject.__getattr__() orobject.__getattribute__(). (Contributed by INADA Naoki inbpo-32544.)

Searching for certain Unicode characters (like Ukrainian capital “Є” ) in a string was up to 25 times slower than searching for other characters. It is now only 3 times slower in the worst case. (Contributed by Serhiy Storchaka inbpo-24821.)

Thecollections.namedtuple()factory has been reimplemented to make the creation of named tuples 4 to 6 times faster. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger inbpo-28638.)

date.fromordinal()anddate.fromtimestamp()are now up to 30% faster in the common case. (Contributed by Paul Ganssle inbpo-32403.)

Theos.fwalk()function is now up to 2 times faster thanks to the use ofos.scandir(). (Contributed by Serhiy Storchaka inbpo-25996.)

The speed of theshutil.rmtree()function has been improved by 20–40% thanks to the use of theos.scandir()function. (Contributed by Serhiy Storchaka inbpo-28564.)

Optimized case-insensitive matching and searching ofregular expressions.Searching some patterns can now be up to 20 times faster. (Contributed by Serhiy Storchaka inbpo-30285.)

re.compile()now convertsflagsparameter to int object if it isRegexFlag.It is now as fast as Python 3.5, and faster than Python 3.6 by about 10% depending on the pattern. (Contributed by INADA Naoki inbpo-31671.)

Themodify()methods of classes selectors.EpollSelector,selectors.PollSelector andselectors.DevpollSelectormay be around 10% faster under heavy loads. (Contributed by Giampaolo Rodola’ inbpo-30014)

Constant folding has been moved from the peephole optimizer to the new AST optimizer, which is able perform optimizations more consistently. (Contributed by Eugene Toder and INADA Naoki inbpo-29469and bpo-11549.)

Most functions and methods inabchave been rewritten in C. This makes creation of abstract base classes, and callingisinstance() andissubclass()on them 1.5x faster. This also reduces Python start-up time by up to 10%. (Contributed by Ivan Levkivskyi and INADA Naoki inbpo-31333)

Significant speed improvements to alternate constructors for datetime.dateanddatetime.datetimeby using fast-path constructors when not constructing subclasses. (Contributed by Paul Ganssle inbpo-32403)

The speed of comparison ofarray.arrayinstances has been improved considerably in certain cases. It is now from 10x to 70x faster when comparing arrays holding values of the same integer type. (Contributed by Adrian Wielgosik inbpo-24700.)

Themath.erf()andmath.erfc()functions now use the (faster) C library implementation on most platforms. (Contributed by Serhiy Storchaka inbpo-26121.)

Other CPython Implementation Changes

  • Trace hooks may now opt out of receiving thelineand opt into receiving theopcodeevents from the interpreter by setting the corresponding new f_trace_linesandf_trace_opcodesattributes on the frame being traced. (Contributed by Nick Coghlan inbpo-31344.)

  • Fixed some consistency problems with namespace package module attributes. Namespace module objects now have an__file__that is set toNone (previously unset), and their__spec__.originis also set toNone (previously the string"namespace"). Seebpo-32305.Also, the namespace module object’s__spec__.loaderis set to the same value as __loader__(previously, the former was set toNone). See bpo-32303.

  • Thelocals()dictionary now displays in the lexical order that variables were defined. Previously, the order was undefined. (Contributed by Raymond Hettinger inbpo-32690.)

  • Thedistutilsuploadcommand no longer tries to change CR end-of-line characters to CRLF. This fixes a corruption issue with sdists that ended with a byte equivalent to CR. (Contributed by Bo Bayles inbpo-32304.)

Deprecated Python Behavior

Yield expressions (bothyieldandyieldfromclauses) are now deprecated in comprehensions and generator expressions (aside from the iterable expression in the leftmostforclause). This ensures that comprehensions always immediately return a container of the appropriate type (rather than potentially returning agenerator iteratorobject), while generator expressions won’t attempt to interleave their implicit output with the output from any explicit yield expressions. In Python 3.7, such expressions emit DeprecationWarningwhen compiled, in Python 3.8 this will be a SyntaxError. (Contributed by Serhiy Storchaka inbpo-10544.)

Returning a subclass ofcomplexfromobject.__complex__()is deprecated and will be an error in future Python versions. This makes __complex__()consistent withobject.__int__()and object.__float__(). (Contributed by Serhiy Storchaka inbpo-28894.)

Deprecated Python modules, functions and methods

aifc

aifc.openfp()has been deprecated and will be removed in Python 3.9. Useaifc.open()instead. (Contributed by Brian Curtin inbpo-31985.)

asyncio

Support for directlyawait-ing instances ofasyncio.Lockand other asyncio synchronization primitives has been deprecated. An asynchronous context manager must be used in order to acquire and release the synchronization resource. (Contributed by Andrew Svetlov inbpo-32253.)

Theasyncio.Task.current_task()andasyncio.Task.all_tasks() methods have been deprecated. (Contributed by Andrew Svetlov inbpo-32250.)

collections

In Python 3.8, the abstract base classes incollections.abcwill no longer be exposed in the regularcollectionsmodule. This will help create a clearer distinction between the concrete classes and the abstract base classes. (Contributed by Serhiy Storchaka inbpo-25988.)

dbm

dbm.dumbnow supports reading read-only files and no longer writes the index file when it is not changed. A deprecation warning is now emitted if the index file is missing and recreated in the'r'and'w' modes (this will be an error in future Python releases). (Contributed by Serhiy Storchaka inbpo-28847.)

enum

In Python 3.8, attempting to check for non-Enum objects inEnum classes will raise aTypeError(e.g.1inColor); similarly, attempting to check for non-Flag objects in aFlagmember will raiseTypeError(e.g.1inPerm.RW); currently, both operations returnFalseinstead. (Contributed by Ethan Furman inbpo-33217.)

gettext

Using non-integer value for selecting a plural form ingettextis now deprecated. It never correctly worked. (Contributed by Serhiy Storchaka inbpo-28692.)

importlib

Methods MetaPathFinder.find_module() (replaced by MetaPathFinder.find_spec()) and PathEntryFinder.find_loader() (replaced by PathEntryFinder.find_spec()) both deprecated in Python 3.4 now emitDeprecationWarning. (Contributed by Matthias Bussonnier inbpo-29576.)

Theimportlib.abc.ResourceLoaderABC has been deprecated in favour ofimportlib.abc.ResourceReader.

locale

locale.format()has been deprecated, uselocale.format_string() instead. (Contributed by Garvit inbpo-10379.)

macpath

Themacpathis now deprecated and will be removed in Python 3.8. (Contributed by Chi Hsuan Yen inbpo-9850.)

threading

dummy_threadingand_dummy_threadhave been deprecated. It is no longer possible to build Python with threading disabled. Usethreadinginstead. (Contributed by Antoine Pitrou inbpo-31370.)

socket

The silent argument value truncation insocket.htons()and socket.ntohs()has been deprecated. In future versions of Python, if the passed argument is larger than 16 bits, an exception will be raised. (Contributed by Oren Milman inbpo-28332.)

ssl

ssl.wrap_socket()is deprecated. Use ssl.SSLContext.wrap_socket()instead. (Contributed by Christian Heimes inbpo-28124.)

sunau

sunau.openfp()has been deprecated and will be removed in Python 3.9. Usesunau.open()instead. (Contributed by Brian Curtin inbpo-31985.)

sys

Deprecatedsys.set_coroutine_wrapper()and sys.get_coroutine_wrapper().

The undocumentedsys.callstats()function has been deprecated and will be removed in a future Python version. (Contributed by Victor Stinner inbpo-28799.)

wave

wave.openfp()has been deprecated and will be removed in Python 3.9. Usewave.open()instead. (Contributed by Brian Curtin inbpo-31985.)

Deprecated functions and types of the C API

FunctionPySlice_GetIndicesEx()is deprecated and replaced with a macro ifPy_LIMITED_APIis not set or set to a value in the range between0x03050400and0x03060000(not inclusive), or is0x03060100 or higher. (Contributed by Serhiy Storchaka inbpo-27867.)

PyOS_AfterFork()has been deprecated. UsePyOS_BeforeFork(), PyOS_AfterFork_Parent()orPyOS_AfterFork_Child()instead. (Contributed by Antoine Pitrou inbpo-16500.)

Platform Support Removals

  • FreeBSD 9 and older are no longer officially supported.

  • For full Unicode support, including within extension modules, *nix platforms are now expected to provide at least one ofC.UTF-8(full locale), C.utf8(full locale) orUTF-8(LC_CTYPE-only locale) as an alternative to the legacyASCII-basedClocale.

  • OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython 3.7 with SSL/TLS support on older platforms still using these versions requires custom build options that link to a more recent version of OpenSSL.

    Notably, this issue affects the Debian 8 (aka “jessie” ) and Ubuntu 14.04 (aka “Trusty” ) LTS Linux distributions, as they still use OpenSSL 1.0.1 by default.

    Debian 9 ( “stretch” ) and Ubuntu 16.04 ( “xenial” ), as well as recent releases of other LTS Linux releases (e.g. RHEL/CentOS 7.5, SLES 12-SP3), use OpenSSL 1.0.2 or later, and remain supported in the default build configuration.

    CPython’s ownCI configuration fileprovides an example of using the SSL compatibility testing infrastructurein CPython’s test suite to build and link against OpenSSL 1.1.0 rather than an outdated system provided OpenSSL.

API and Feature Removals

The following features and APIs have been removed from Python 3.7:

  • Theos.stat_float_times()function has been removed. It was introduced in Python 2.3 for backward compatibility with Python 2.2, and was deprecated since Python 3.1.

  • Unknown escapes consisting of'\'and an ASCII letter in replacement templates forre.sub()were deprecated in Python 3.5, and will now cause an error.

  • Removed support of theexcludeargument intarfile.TarFile.add(). It was deprecated in Python 2.7 and 3.2. Use thefilterargument instead.

  • Thentpath.splitunc()function was deprecated in Python 3.1, and has now been removed. Usesplitdrive() instead.

  • collections.namedtuple()no longer supports theverboseparameter or_sourceattribute which showed the generated source code for the named tuple class. This was part of an optimization designed to speed-up class creation. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger inbpo-28638.)

  • Functionsbool(),float(),list()andtuple()no longer take keyword arguments. The first argument ofint()can now be passed only as positional argument.

  • Removed previously deprecated in Python 2.4 classesPlist,Dictand _InternalDictin theplistlibmodule. Dict values in the result of functionsreadPlist()and readPlistFromBytes()are now normal dicts. You no longer can use attribute access to access items of these dictionaries.

  • Theasyncio.windows_utils.socketpair()function has been removed. Use thesocket.socketpair()function instead, it is available on all platforms since Python 3.5. asyncio.windows_utils.socketpairwas just an alias to socket.socketpairon Python 3.5 and newer.

  • asynciono longer exports theselectorsand _overlappedmodules asasyncio.selectorsand asyncio._overlapped.Replacefromasyncioimportselectorswith importselectors.

  • Direct instantiation ofssl.SSLSocketandssl.SSLObject objects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were supposed to use ssl.wrap_socket()orssl.SSLContext. (Contributed by Christian Heimes inbpo-32951.)

  • The unuseddistutilsinstall_misccommand has been removed. (Contributed by Eric N. Vander Weele inbpo-29218.)

Module Removals

Thefpectlmodule has been removed. It was never enabled by default, never worked correctly on x86-64, and it changed the Python ABI in ways that caused unexpected breakage of C extensions. (Contributed by Nathaniel J. Smith inbpo-29137.)

Windows-only Changes

The python launcher, (py.exe), can accept 32 & 64 bit specifierswithout having to specify a minor version as well. Sopy-3-32andpy-3-64 become valid as well aspy-3.7-32,also the -m-64 and -m.n-64 forms are now accepted to force 64 bit python even if 32 bit would have otherwise been used. If the specified version is not available py.exe will error exit. (Contributed by Steve Barnes inbpo-30291.)

The launcher can be run aspy-0to produce a list of the installed pythons, with default marked with an asterisk.Runningpy-0pwill include the paths. If py is run with a version specifier that cannot be matched it will also print theshort formlist of available specifiers. (Contributed by Steve Barnes inbpo-30362.)

Porting to Python 3.7

This section lists previously described changes and other bugfixes that may require changes to your code.

Changes in Python Behavior

  • asyncandawaitnames are now reserved keywords. Code using these names as identifiers will now raise aSyntaxError. (Contributed by Jelle Zijlstra inbpo-30406.)

  • PEP 479is enabled for all code in Python 3.7, meaning that StopIterationexceptions raised directly or indirectly in coroutines and generators are transformed intoRuntimeError exceptions. (Contributed by Yury Selivanov inbpo-32670.)

  • object.__aiter__()methods can no longer be declared as asynchronous. (Contributed by Yury Selivanov inbpo-31709.)

  • Due to an oversight, earlier Python versions erroneously accepted the following syntax:

    f(1forxin[1],)
    
    classC(1forxin[1]):
    pass
    

    Python 3.7 now correctly raises aSyntaxError,as a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side, and the duplication of the parentheses can be omitted only on calls. (Contributed by Serhiy Storchaka inbpo-32012andbpo-32023.)

  • When using the-mswitch, the initial working directory is now added tosys.path,rather than an empty string (which dynamically denoted the current working directory at the time of each import). Any programs that are checking for the empty string, or otherwise relying on the previous behaviour, will need to be updated accordingly (e.g. by also checking for os.getcwd()oros.path.dirname(__main__.__file__),depending on why the code was checking for the empty string in the first place).

Changes in the Python API

  • socketserver.ThreadingMixIn.server_close()now waits until all non-daemon threads complete. Set the new socketserver.ThreadingMixIn.block_on_closeclass attribute to Falseto get the pre-3.7 behaviour. (Contributed by Victor Stinner inbpo-31233andbpo-33540.)

  • socketserver.ForkingMixIn.server_close()now waits until all child processes complete. Set the new socketserver.ForkingMixIn.block_on_closeclass attribute toFalse to get the pre-3.7 behaviour. (Contributed by Victor Stinner inbpo-31151andbpo-33540.)

  • Thelocale.localeconv()function now temporarily sets theLC_CTYPE locale to the value ofLC_NUMERICin some cases. (Contributed by Victor Stinner inbpo-31900.)

  • pkgutil.walk_packages()now raises aValueErrorifpathis a string. Previously an empty list was returned. (Contributed by Sanyam Khurana inbpo-24744.)

  • A format string argument forstring.Formatter.format() is nowpositional-only. Passing it as a keyword argument was deprecated in Python 3.5. (Contributed by Serhiy Storchaka inbpo-29193.)

  • Attributeskey, valueand coded_valueof class http.cookies.Morselare now read-only. Assigning to them was deprecated in Python 3.5. Use theset()method for setting them. (Contributed by Serhiy Storchaka inbpo-29192.)

  • Themodeargument ofos.makedirs()no longer affects the file permission bits of newly created intermediate-level directories. To set their file permission bits you can set the umask before invoking makedirs(). (Contributed by Serhiy Storchaka inbpo-19930.)

  • Thestruct.Struct.formattype is nowstrinstead of bytes.(Contributed by Victor Stinner inbpo-21071.)

  • parse_multipart()now accepts theencodinganderrors arguments and returns the same results as FieldStorage:for non-file fields, the value associated to a key is a list of strings, not bytes. (Contributed by Pierre Quentel inbpo-29979.)

  • Due to internal changes insocket,callingsocket.fromshare() on a socket created bysocket.sharein older Python versions is not supported.

  • reprforBaseExceptionhas changed to not include the trailing comma. Most exceptions are affected by this change. (Contributed by Serhiy Storchaka inbpo-30399.)

  • reprfordatetime.timedeltahas changed to include the keyword arguments in the output. (Contributed by Utkarsh Upadhyay inbpo-30302.)

  • Becauseshutil.rmtree()is now implemented using theos.scandir() function, the user specified handleronerroris now called with the first argumentos.scandirinstead ofos.listdirwhen listing the directory is failed.

  • Support for nested sets and set operations in regular expressions as in Unicode Technical Standard #18might be added in the future. This would change the syntax. To facilitate this future change aFutureWarning will be raised in ambiguous cases for the time being. That include sets starting with a literal'['or containing literal character sequences'--','&&','~~',and'||'.To avoid a warning, escape them with a backslash. (Contributed by Serhiy Storchaka inbpo-30349.)

  • The result of splitting a string on aregularexpression that could match an empty string has been changed. For example splitting onr'\s*'will now split not only on whitespaces as it did previously, but also on empty strings before all non-whitespace characters and just before the end of the string. The previous behavior can be restored by changing the pattern tor'\s+'.AFutureWarningwas emitted for such patterns since Python 3.5.

    For patterns that match both empty and non-empty strings, the result of searching for all matches may also be changed in other cases. For example in the string'a\n\n',the patternr'(?m)^\s*?$'will not only match empty strings at positions 2 and 3, but also the string'\n'at positions 2–3. To match only blank lines, the pattern should be rewritten asr'(?m)^[^\S\n]*$'.

    re.sub()now replaces empty matches adjacent to a previous non-empty match. For examplere.sub('x*','-','abxd')returns now '-a-b--d-'instead of'-a-b-d-'(the first minus between ‘b’ and ‘d’ replaces ‘x’, and the second minus replaces an empty string between ‘x’ and ‘d’).

    (Contributed by Serhiy Storchaka inbpo-25054andbpo-32308.)

  • Changere.escape()to only escape regex special characters instead of escaping all characters other than ASCII letters, numbers, and'_'. (Contributed by Serhiy Storchaka inbpo-29995.)

  • tracemalloc.Tracebackframes are now sorted from oldest to most recent to be more consistent withtraceback. (Contributed by Jesse Bakker inbpo-32121.)

  • On OSes that supportsocket.SOCK_NONBLOCKor socket.SOCK_CLOEXECbit flags, the socket.typeno longer has them applied. Therefore, checks likeifsock.type==socket.SOCK_STREAM work as expected on all platforms. (Contributed by Yury Selivanov inbpo-32331.)

  • On Windows the default for theclose_fdsargument of subprocess.Popenwas changed fromFalsetoTrue when redirecting the standard handles. If you previously depended on handles being inherited when usingsubprocess.Popenwith standard io redirection, you will have to passclose_fds=Falseto preserve the previous behaviour, or use STARTUPINFO.lpAttributeList.

  • importlib.machinery.PathFinder.invalidate_caches()– which implicitly affectsimportlib.invalidate_caches()– now deletes entries insys.path_importer_cachewhich are set toNone. (Contributed by Brett Cannon inbpo-33169.)

  • Inasyncio, loop.sock_recv(), loop.sock_sendall(), loop.sock_accept(), loop.getaddrinfo(), loop.getnameinfo() have been changed to be proper coroutine methods to match their documentation. Previously, these methods returnedasyncio.Future instances. (Contributed by Yury Selivanov inbpo-32327.)

  • asyncio.Server.socketsnow returns a copy of the internal list of server sockets, instead of returning it directly. (Contributed by Yury Selivanov inbpo-32662.)

  • Struct.formatis now astrinstance instead of abytesinstance. (Contributed by Victor Stinner inbpo-21071.)

  • argparsesubparsers can now be made mandatory by passingrequired=True toArgumentParser.add_subparsers(). (Contributed by Anthony Sottile inbpo-26510.)

  • ast.literal_eval()is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka inbpo-31778.)

  • Calendar.itermonthdates will now consistently raise an exception when a date falls outside of the 0001-01-01through9999-12-31range. To support applications that cannot tolerate such exceptions, the new Calendar.itermonthdays3and Calendar.itermonthdays4can be used. The new methods return tuples and are not restricted by the range supported by datetime.date. (Contributed by Alexander Belopolsky inbpo-28292.)

  • collections.ChainMapnow preserves the order of the underlying mappings. (Contributed by Raymond Hettinger inbpo-32792.)

  • Thesubmit()method ofconcurrent.futures.ThreadPoolExecutor andconcurrent.futures.ProcessPoolExecutornow raises aRuntimeErrorif called during interpreter shutdown. (Contributed by Mark Nemec inbpo-33097.)

  • Theconfigparser.ConfigParserconstructor now usesread_dict() to process the default values, making its behavior consistent with the rest of the parser. Non-string keys and values in the defaults dictionary are now being implicitly converted to strings. (Contributed by James Tocknell inbpo-23835.)

  • Several undocumented internal imports were removed. One example is thatos.errnois no longer available; useimporterrno directly instead. Note that such undocumented internal imports may be removed any time without notice, even in micro version releases.

Changes in the C API

The functionPySlice_GetIndicesEx()is considered unsafe for resizable sequences. If the slice indices are not instances ofint, but objects that implement the__index__()method, the sequence can be resized after passing its length toPySlice_GetIndicesEx().This can lead to returning indices out of the length of the sequence. For avoiding possible problems use new functionsPySlice_Unpack()and PySlice_AdjustIndices(). (Contributed by Serhiy Storchaka inbpo-27867.)

CPython bytecode changes

There are two new opcodes:LOAD_METHODandCALL_METHOD. (Contributed by Yury Selivanov and INADA Naoki inbpo-26110.)

TheSTORE_ANNOTATIONopcode has been removed. (Contributed by Mark Shannon inbpo-32550.)

Windows-only Changes

The file used to overridesys.pathis now called <python-executable>._pthinstead of'sys.path'. SeeFinding modulesfor more information. (Contributed by Steve Dower inbpo-28137.)

Other CPython implementation changes

In preparation for potential future changes to the public CPython runtime initialization API (seePEP 432for an initial, but somewhat outdated, draft), CPython’s internal startup and configuration management logic has been significantly refactored. While these updates are intended to be entirely transparent to both embedding applications and users of the regular CPython CLI, they’re being mentioned here as the refactoring changes the internal order of various operations during interpreter startup, and hence may uncover previously latent defects, either in embedding applications, or in CPython itself. (Initially contributed by Nick Coghlan and Eric Snow as part of bpo-22257,and further updated by Nick, Eric, and Victor Stinner in a number of other issues). Some known details affected:

  • PySys_AddWarnOptionUnicode()is not currently usable by embedding applications due to the requirement to create a Unicode object prior to callingPy_Initialize.UsePySys_AddWarnOption()instead.

  • warnings filters added by an embedding application with PySys_AddWarnOption()should now more consistently take precedence over the default filters set by the interpreter

Due to changes in the way the default warnings filters are configured, settingPy_BytesWarningFlagto a value greater than one is no longer sufficient to both emitBytesWarningmessages and have them converted to exceptions. Instead, the flag must be set (to cause the warnings to be emitted in the first place), and an expliciterror::BytesWarning warnings filter added to convert them to exceptions.

Due to a change in the way docstrings are handled by the compiler, the implicitreturnNonein a function body consisting solely of a docstring is now marked as occurring on the same line as the docstring, not on the function’s header line.

The current exception state has been moved from the frame object to the co-routine. This simplified the interpreter and fixed a couple of obscure bugs caused by having swap exception state when entering or exiting a generator. (Contributed by Mark Shannon inbpo-25612.)

Notable changes in Python 3.7.1

Starting in 3.7.1,Py_Initialize()now consistently reads and respects all of the same environment settings asPy_Main()(in earlier Python versions, it respected an ill-defined subset of those environment variables, while in Python 3.7.0 it didn’t read any of them due tobpo-34247). If this behavior is unwanted, setPy_IgnoreEnvironmentFlagto 1 before callingPy_Initialize().

In 3.7.1 the C API for Context Variables was updatedto use PyObjectpointers. See alsobpo-34762.

In 3.7.1 thetokenizemodule now implicitly emits aNEWLINEtoken when provided with input that does not have a trailing new line. This behavior now matches what the C tokenizer does internally. (Contributed by Ammar Askar inbpo-33899.)

Notable changes in Python 3.7.2

In 3.7.2,venvon Windows no longer copies the original binaries, but creates redirector scripts namedpython.exeandpythonw.exeinstead. This resolves a long standing issue where all virtual environments would have to be upgraded or recreated with each Python update. However, note that this release will still require recreation of virtual environments in order to get the new scripts.

Notable changes in Python 3.7.6

Due to significant security concerns, thereuse_addressparameter of asyncio.loop.create_datagram_endpoint()is no longer supported. This is because of the behavior of the socket optionSO_REUSEADDRin UDP. For more details, see the documentation forloop.create_datagram_endpoint(). (Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov in bpo-37228.)

Notable changes in Python 3.7.10

Earlier Python versions allowed using both;and&as query parameter separators inurllib.parse.parse_qs()and urllib.parse.parse_qsl().Due to security concerns, and to conform with newer W3C recommendations, this has been changed to allow only a single separator key, with&as the default. This change also affects cgi.parse()andcgi.parse_multipart()as they use the affected functions internally. For more details, please see their respective documentation. (Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin inbpo-42967.)

Notable changes in Python 3.7.11

A security fix alters theftplib.FTPbehavior to not trust the IPv4 address sent from the remote server when setting up a passive data channel. We reuse the ftp server IP address instead. For unusual code requiring the old behavior, set atrust_server_pasv_ipv4_address attribute on your FTP instance toTrue.(Seegh-87451)

The presence of newline or tab characters in parts of a URL allows for some forms of attacks. Following the WHATWG specification that updates RFC 3986, ASCII newline\n,\rand tab\tcharacters are stripped from the URL by the parserurllib.parse()preventing such attacks. The removal characters are controlled by a new module level variable urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE.(Seegh-88048)

Notable security feature in 3.7.14

Converting betweenintandstrin bases other than 2 (binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal) now raises aValueErrorif the number of digits in string form is above a limit to avoid potential denial of service attacks due to the algorithmic complexity. This is a mitigation forCVE-2020-10735. This limit can be configured or disabled by environment variable, command line flag, orsysAPIs. See theinteger string conversion length limitationdocumentation. The default limit is 4300 digits in string form.