Python 3.7 有什麼新功能

編輯者:

Elvis Pranskevichus <elvis@magic.io>

本文介紹了 Python 3.7 與 3.6 相比多了哪些新功能。Python 3.7 已於 2018 年 6 月 27 日發布。有關完整詳細資訊,請參閱changelog

發布重點摘要

新增語法特性:

  • PEP 563, postponed evaluation of type annotations.

Backwards incompatible syntax changes:

新的函式庫模組:

新的內建功能:

Python 資料模型改進:

  • PEP 562, customization of access tomodule attributes.

  • PEP 560, core support for typing module andgeneric types.

  • the insertion-order preservation nature ofdictobjectshas been declared to be an officialpart of the Python language spec.

標準函式庫中的顯著改進

CPython 實作改進:

C API 改進:

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

Documentation improvements:

This release features notable performance improvements in many areas.The最佳化 section lists them in detail.

For a list of changes that may affect compatibility with previous Pythonreleases please refer to the移植至 Python 3.7 section.

新增功能

PEP 563:延後評估註釋

The advent of type hints in Python uncovered two glaring usability issueswith the functionality of annotations added inPEP 3107 and refinedfurther inPEP 526:

  • annotations could only use names which were already available in thecurrent scope, in other words they didn't support forward referencesof any kind; and

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

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

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

classC:@classmethoddeffrom_string(cls,source:str)->C:...defvalidate_b(self,obj:B)->bool:...classB:...

Since this change breaks compatibility, the new behavior needs to be enabledon a per-module basis in Python 3.7 using a__future__ import:

from__future__importannotations

It will become the default in Python 3.10.

也參考

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 sensibledefault strategy for handling the "7-bit ASCII" text encoding assumptioncurrently implied by the use of the default C or POSIX locale on non-Windowsplatforms.

PEP 538 updates the default interpreter command line interface toautomatically coerce that locale to an available UTF-8 based locale asdescribed in the documentation of the newPYTHONCOERCECLOCALEenvironment variable. Automatically settingLC_CTYPE this way means thatboth the core interpreter and locale-aware C extensions (such asreadline) will assume the use of UTF-8 as the default text encoding,rather than ASCII.

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

As part of this change, the default error handler forstdin andstdout is nowsurrogateescape (rather thanstrict) whenusing any of the defined coercion target locales (currentlyC.UTF-8,C.utf8, andUTF-8). The default error handler forstderrcontinues to bebackslashreplace, regardless of locale.

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

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

也參考

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

由 Nick Coghlan 撰寫 PEP 與實作。

PEP 540: Forced UTF-8 Runtime Mode

The new-Xutf8 command line option andPYTHONUTF8environment variable can be used to enable thePython UTF-8 Mode.

When in UTF-8 mode, CPython ignores the locale settings, and uses theUTF-8 encoding by default. The error handlers forsys.stdin andsys.stdout streams are set tosurrogateescape.

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

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

The UTF-8 mode is enabled by default when the locale isC orPOSIX, andthePEP 538 locale coercion feature fails to change it to a UTF-8 basedalternative (whether that failure is due toPYTHONCOERCECLOCALE=0 being set,LC_ALL being set, or the lack of a suitable target locale).

也參考

PEP 540 -- Add a new UTF-8 mode

由 Victor Stinner 撰寫 PEP 與實作

PEP 553: Built-inbreakpoint()

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

Built-inbreakpoint() callssys.breakpointhook(). By default, thelatter importspdb and then callspdb.set_trace(), but by bindingsys.breakpointhook() to the function of your choosing,breakpoint() canenter any debugger. Additionally, the environment variablePYTHONBREAKPOINT can be set to the callable of your debugger ofchoice. SetPYTHONBREAKPOINT=0 to completely disable built-inbreakpoint().

也參考

PEP 553 -- Built-in breakpoint()

由 Barry Warsaw 撰寫 PEP 與實作

PEP 539: New C API for Thread-Local Storage

While Python provides a C API for thread-local storage support; the existingThread Local Storage (TLS) API has usedint to represent TLS keys across all platforms. This has notgenerally been a problem for officially support platforms, but that is neitherPOSIX-compliant, nor portable in any practical sense.

PEP 539 changes this by providing a newThread Specific Storage (TSS)API to CPython which supersedes use of theexisting TLS API within the CPython interpreter, while deprecating the existingAPI. The TSS API uses a new typePy_tss_t instead ofintto represent TSS keys--an opaque type the definition of which may depend onthe underlying TLS implementation. Therefore, this will allow to build CPythonon platforms where the native TLS key is defined in a way that cannot be safelycast toint.

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

也參考

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

PEP 由 Erik M. Bray 撰寫;由 Masayuki Yamamoto 實作。

PEP 562: Customization of Access to Module Attributes

Python 3.7 allows defining__getattr__() on modules and will callit 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 deprecationand lazy loading.

也參考

PEP 562 --__getattr____dir__ 模組

由 Ivan Levkivskyi 撰寫 PEP 與實作

PEP 564: New Time Functions With Nanosecond Resolution

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

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

Measurementsshow that on Linux and Windows the resolution oftime.time_ns() isapproximately 3 times better than that oftime.time().

也參考

PEP 564 -- Add new time functions with nanosecond resolution

由 Victor Stinner 撰寫 PEP 與實作

PEP 565: Show DeprecationWarning in__main__

The default handling ofDeprecationWarning has been changed such thatthese warnings are once more shown by default, but only when the codetriggering them is running directly in the__main__ module. As a result,developers of single file scripts and those using Python interactively shouldonce again start seeing deprecation warnings for the APIs they use, butdeprecation warnings triggered by imported application, library and frameworkmodules will continue to be hidden by default.

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

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

  • DeprecationWarning: displayed by default only in__main__ and whenrunning tests, recommended for warnings intended to be seen by other Pythondevelopers where a version upgrade may result in changed behaviour or anerror.

  • PendingDeprecationWarning: displayed by default only when runningtests, intended for cases where a future version upgrade will change thewarning category toDeprecationWarning orFutureWarning.

Previously bothDeprecationWarning andPendingDeprecationWarningwere only visible when running tests, which meant that developers primarilywriting single file scripts or using Python interactively could be surprisedby breaking changes in the APIs they used.

也參考

PEP 565 -- 在__main__ 中顯示 DeprecationWarning

由 Nick Coghlan 撰寫 PEP 與實作

PEP 560: Core Support fortyping module and Generic Types

InitiallyPEP 484 was designed in such way that it would not introduceanychanges to the core CPython interpreter. Now type hints and thetypingmodule 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 specialconstructs intyping. As a result, the speed of various operationswith types increased up to 7 times, the generic types can be used withoutmetaclass conflicts, and several long standing bugs intyping module arefixed.

也參考

PEP 560 -- Core support for typing module and generic types

由 Ivan Levkivskyi 撰寫 PEP 與實作

PEP 552: Hash-based .pyc Files

Python has traditionally checked the up-to-dateness of bytecode cache files(i.e.,.pyc files) by comparing the source metadata (last-modified timestampand size) with source metadata saved in the cache file header when it wasgenerated. While effective, this invalidation method has its drawbacks. Whenfilesystem timestamps are too coarse, Python can miss source updates, leading touser confusion. Additionally, having a timestamp in the cache file isproblematic forbuild reproducibility andcontent-based build systems.

PEP 552 extends the pyc format to allow the hash of the source file to beused for invalidation instead of the source timestamp. Such.pyc files arecalled "hash-based". By default, Python still uses timestamp-based invalidationand does not generate hash-based.pyc files at runtime. Hash-based.pycfiles may be generated withpy_compile orcompileall.

Hash-based.pyc files come in two variants: checked and unchecked. Pythonvalidates checked hash-based.pyc files against the corresponding sourcefiles at runtime but doesn't do so for unchecked hash-based pycs. Uncheckedhash-based.pyc files are a useful performance optimization for environmentswhere a system external to Python (e.g., the build system) is responsible forkeeping.pyc files up-to-date.

更多資訊請見Cached bytecode invalidation

也參考

PEP 552 -- Deterministic pycs

由 Benjamin Peterson 撰寫 PEP 與實作

PEP 545:Python 文件翻譯

PEP 545 describes the process of creating and maintaining Pythondocumentation translations.

Three new translations have been added:

也參考

PEP 545 -- Python 文件翻譯

PEP 由 Julien Palard、Inada Naoki 與 Victor Stinner 撰寫。

Python Development Mode (-X dev)

The new-Xdev command line option or the newPYTHONDEVMODE environment variable can be used to enablePython Development Mode. When in development mode, Python performsadditional runtime checks that are too expensive to be enabled by default.SeePython Development Mode documentation for the fulldescription.

其他語言更動

  • Anawait expression and comprehensions containing anasyncfor clause were illegal in the expressions informatted string literals due to a problem with theimplementation. In Python 3.7 this restriction was lifted.

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

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

  • str,bytes, andbytearray gained support forthe newisascii() method, which can be used totest if a string or bytes contain only the ASCII characters.(Contributed by INADA Naoki inbpo-32677.)

  • ImportError now displays module name and module__file__ path whenfrom...import... fails. (Contributed by Matthias Bussonnier inbpo-29546.)

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

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

  • In order to better support dynamic creation of stack traces,types.TracebackType can now be instantiated from Python code, andthetb_next attribute ontracebacks is now writable.(Contributed by Nathaniel J. Smith inbpo-30579.)

  • When using the-m switch,sys.path[0] is now eagerly expandedto the full starting directory path, rather than being left as the emptydirectory (which allows imports from thecurrent working directory at thetime when an import occurs)(Contributed by Nick Coghlan inbpo-33053.)

  • The new-Ximporttime option or thePYTHONPROFILEIMPORTTIME environment variable can be used to showthe timing of each module import.(Contributed by Inada Naoki inbpo-31415.)

新模組

contextvars

The newcontextvars module and a set ofnew C APIs introducesupport forcontext variables. Context variables are conceptuallysimilar to thread-local variables. Unlike TLS, context variablessupport asynchronous code correctly.

Theasyncio anddecimal modules have been updated to useand support context variables out of the box. Particularly the activedecimal context is now stored in a context variable, which allowsdecimal operations to work with the correct context in asynchronous code.

也參考

PEP 567 -- Context Variables

由 Yury Selivanov 撰寫 PEP 與實作

dataclasses

The newdataclass() decorator provides a way to declaredata classes. A data class describes its attributes using class variableannotations. Its constructor and other magic methods, such as__repr__(),__eq__(), and__hash__() are generated automatically.

範例:

@dataclassclassPoint:x:floaty:floatz:float=0.0p=Point(1.5,2.5)print(p)# produces "Point(x=1.5, y=2.5, z=0.0)"

也參考

PEP 557 -- Data Classes

由 Eric V. Smith 撰寫 PEP 與實作

importlib.resources

The newimportlib.resources module provides several new APIs and onenew ABC for access to, opening, and readingresources inside packages.Resources are roughly similar to files inside packages, but they needn'tbe actual files on the physical file system. Module loaders can provide aget_resource_reader() function which returnsaimportlib.abc.ResourceReader instance to support thisnew API. Built-in file path loaders and zip file loaders both support this.

由 Barry Warsaw 與 Brett Cannon 在bpo-32248 中貢獻。

也參考

importlib_resources-- a PyPI backport for earlier Python versions.

改進的模組

argparse

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

asyncio

Theasyncio module has received many new features, usability andperformance improvements. Notable changesinclude:

Severalasyncio APIs have beendeprecated.

binascii

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

calendar

TheHTMLCalendar class has new class attributes which easethe 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_mode parameter,which can be used to enablehash-based .pyc invalidation. The invalidationmode can also be specified on the command line using the new--invalidation-mode argument.(Contributed by Benjamin Peterson inbpo-31650.)

concurrent.futures

ProcessPoolExecutor andThreadPoolExecutor nowsupport the newinitializer andinitargs constructor arguments.(Contributed by Antoine Pitrou inbpo-21423.)

TheProcessPoolExecutorcan now take the multiprocessing context via the newmp_context argument.(Contributed by Thomas Moreau inbpo-31540.)

contextlib

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

The newasynccontextmanager(),AbstractAsyncContextManager, andAsyncExitStack have been added tocomplement their synchronous counterparts. (Contributedby Jelle Zijlstra inbpo-29679 andbpo-30241,and by Alexander Mohr and Ilya Kulakov inbpo-29302.)

cProfile

ThecProfile command line now accepts-mmodule_name as analternative to script path. (Contributed by Sanyam Khurana inbpo-21862.)

crypt

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

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

datetime

The newdatetime.fromisoformat()method constructs adatetime object from a stringin one of the formats output bydatetime.isoformat().(Contributed by Paul Ganssle inbpo-15873.)

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

dbm

dbm.dumb now supports reading read-only files and no longer writes theindex file when it is not changed.

decimal

Thedecimal module now usescontext variablesto store the decimal context.(Contributed by Yury Selivanov inbpo-32630.)

dis

Thedis() function is now able todisassemble nested code objects (the code of comprehensions, generatorexpressions and nested functions, and the code used for building nestedclasses). The maximum depth of disassembly recursion is controlled bythe newdepth parameter.(Contributed by Serhiy Storchaka inbpo-11822.)

distutils

README.rst is now included in the list of distutils standard READMEs andtherefore included in source distributions.(Contributed by Ryan Gonzalez inbpo-11913.)

enum

TheEnum learned the new_ignore_ class property,which allows listing the names of properties which should not becomeenum members.(Contributed by Ethan Furman inbpo-31801.)

In Python 3.8, attempting to check for non-Enum objects inEnumclasses will raise aTypeError (e.g.1inColor); similarly,attempting to check for non-Flag objects in aFlag member willraiseTypeError (e.g.1inPerm.RW); currently, both operationsreturnFalse instead and are deprecated.(Contributed by Ethan Furman inbpo-33217.)

functools

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

gc

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

hmac

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

http.client

HTTPConnection andHTTPSConnectionnow support the newblocksize argument for improved upload throughput.(Contributed by Nir Soffer inbpo-31945.)

http.server

SimpleHTTPRequestHandler now supports the HTTPIf-Modified-Since header. The server returns the 304 response status ifthe target file was not modified after the time specified in the header.(Contributed by Pierre Quentel inbpo-29654.)

SimpleHTTPRequestHandler accepts the newdirectoryargument, in addition to the new--directory command line argument.With this parameter, the server serves the specified directory, by default ituses the current working directory.(Contributed by Stéphane Wirtel and Julien Palard inbpo-28707.)

The newThreadingHTTPServer classuses threads to handle requests usingThreadingMixin.It is used whenhttp.server is 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-levelfunctions and classes.(Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedyinbpo-1612262.)

The Settings dialog (Options, Configure IDLE) has been partly rewrittento 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 thatusers 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 reimplementedas normal features. Their settings have been moved from the Extensions tabto other dialog tabs.(Contributed by Charles Wohlganger and Terry Jan Reedy inbpo-27099.)

Editor code context option revised. Box displays all context lines up tomaxlines. Clicking on a context line jumps the editor to that line. Contextcolors 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 Windows8.1+ or 10, with DPI compatibility properties of the Python binaryunchanged, and a monitor resolution greater than 96 DPI, this shouldmake 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 theSettings dialog. Fewer, but possibly extra long, lines can be squeezed byright clicking on the output. Squeezed output can be expanded in placeby double-clicking the button or into the clipboard or a separate windowby 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 customizedsettings. Any command line arguments entered are added to sys.argv.They re-appear in the box for the next customized run. One can alsosuppress the normal Shell main module restart. (Contributed by CherylSabella, Terry Jan Reedy, and others inbpo-5680 andbpo-37627.)

New in 3.7.5:

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

importlib

Theimportlib.abc.ResourceReader ABC was introduced tosupport the loading of resources from packages. See alsoimportlib.resources.(Contributed by Barry Warsaw, Brett Cannon inbpo-32248.)

importlib.reload() now raisesModuleNotFoundError if the modulelacks a spec.(Contributed by Garvit Khatri inbpo-29851.)

importlib.find_spec() now raisesModuleNotFoundError instead ofAttributeError if 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 ofthe passed source. Ahash-based .pyc fileembeds 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-30526 andINADA Naoki inbpo-15216.)

ipaddress

The newsubnet_of() andsupernet_of() methods ofipaddress.IPv6Network andipaddress.IPv4Network canbe used for network containment tests.(Contributed by Michel Albert and Cheryl Sabella inbpo-20825.)

itertools

itertools.islice() now acceptsinteger-likeobjects as start, stop,and slice arguments.(Contributed by Will Roberts inbpo-30537.)

locale

The newmonetary argument tolocale.format_string() can be usedto make the conversion use monetary thousands separators andgrouping strings. (Contributed by Garvit inbpo-10379.)

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

logging

Logger instances 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 inconfiguration passed tologging.config.fileConfig().(Contributed by Preston Landers inbpo-31080.)

math

The newmath.remainder() function implements the IEEE 754-style remainderoperation. (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 usedto close theMSI database.(Contributed by Berker Peksag inbpo-20486.)

multiprocessing

The newProcess.close() methodexplicitly closes the process object and releases all resources associatedwith it.ValueError is raised if the underlying process is stillrunning.(Contributed by Antoine Pitrou inbpo-30596.)

The newProcess.kill() method canbe used to terminate the process using theSIGKILL signal on Unix.(Contributed by Vitor Pereira inbpo-30794.)

Non-daemonic threads created byProcess are nowjoined on process exit.(Contributed by Antoine Pitrou inbpo-18966.)

os

os.fwalk() now accepts thepath argument 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 Pythoncallbacks to be executed at process fork.(Contributed by Antoine Pitrou inbpo-16500.)

Addedos.preadv() (combine the functionality ofos.readv() andos.pread()) andos.pwritev() functions (combine the functionalityofos.writev() andos.pwrite()). (Contributed by Pablo Galindo inbpo-31368.)

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

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

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

pathlib

The newPath.is_mount() method is now availableon 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 optionalheader keyword-onlyargument. If given, it is printed to the console just before debuggingbegins. (Contributed by Barry Warsaw inbpo-31389.)

pdb command line now accepts-mmodule_name as an alternative toscript file. (Contributed by Mario Corchero inbpo-32206.)

py_compile

py_compile.compile() -- and by extension,compileall -- nowrespects theSOURCE_DATE_EPOCH environment variable byunconditionally creating.pyc files for hash-based validation.This allows for guaranteeingreproducible builds of.pycfiles when they are created eagerly. (Contributed by Bernhard M. Wiedemanninbpo-29708.)

pydoc

The pydoc server can now bind to an arbitrary hostname specified by thenew-n command-line argument.(Contributed by Feanil Patel inbpo-31128.)

queue

The newSimpleQueue class is an unboundedFIFO queue.(Contributed by Antoine Pitrou inbpo-14976.)

re

The flagsre.ASCII,re.LOCALE andre.UNICODEcan 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.LOCALE flag no longerdepend on the locale at compile time. Locale settings are applied onlywhen the compiled regular expression is used.(Contributed by Serhiy Storchaka inbpo-30215.)

FutureWarning is now emitted if a regular expression containscharacter 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 copiedusingcopy.copy() andcopy.deepcopy().(Contributed by Serhiy Storchaka inbpo-10076.)

signal

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

socket

The newsocket.getblocking() methodreturnsTrue if the socket is in blocking mode andFalse otherwise.(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 bettercompatibility across platforms.(Contributed by Christian Heimes inbpo-32454.)

Thesocket module now exposes thesocket.TCP_CONGESTION(Linux 2.6.13),socket.TCP_USER_TIMEOUT (Linux 2.6.37), andsocket.TCP_NOTSENT_LOWAT (Linux 3.12) constants.(Contributed by Omar Sandoval inbpo-26273 andNathaniel J. Smith inbpo-29728.)

Support forsocket.AF_VSOCK sockets has been added to allowcommunication between virtual machines and their hosts.(Contributed by Cathy Avery inbpo-27584.)

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

socketserver

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

Add a newsocketserver.ForkingMixIn.block_on_close class attribute tosocketserver.ForkingMixIn andsocketserver.ThreadingMixInclasses. Set the class attribute toFalse to get the pre-3.7 behaviour.

sqlite3

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

Thedatabase argument ofsqlite3.connect() now accepts anypath-like object, instead of just a string.(Contributed by Anders Lorentsen inbpo-31843.)

ssl

Thessl module now uses OpenSSL's builtin API instead ofmatch_hostname() to check a host name or an IP address. Valuesare validated during TLS handshake. Any certificate validation errorincluding failing the host name check now raisesSSLCertVerificationError and aborts the handshake with a properTLS Alert message. The new exception contains additional information.Host name validation can be customized withSSLContext.hostname_checks_common_name.(Contributed by Christian Heimes inbpo-31399.)

備註

The improved host name check requires alibssl implementation compatiblewith OpenSSL 1.0.2 or 1.1. Consequently, OpenSSL 0.9.8 and 1.0.1 are nolonger supported (seePlatform Support Removals for more details).The ssl module is mostly compatible with LibreSSL 2.7.2 and newer.

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

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

The default cipher suite selection of thessl module now uses a blacklistapproach rather than a hard-coded whitelist. Python no longer re-enablesciphers that have been blocked by OpenSSL security updates. Default ciphersuite 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, theSSLSocket.server_hostname attributenow stores the expected hostname in A-label form ("xn--pythn-mua.org"),rather than the U-label form ("pythön.org"). (Contributed byNathaniel J. Smith and Christian Heimes inbpo-28414.)

Thessl module has preliminary and experimental support for TLS 1.3 andOpenSSL 1.1.1. At the time of Python 3.7.0 release, OpenSSL 1.1.1 is stillunder development and TLS 1.3 hasn't been finalized yet. The TLS 1.3handshake 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-30622 andbpo-33618)

SSLSocket andSSLObject no longer have a publicconstructor. Direct instantiation was never a documented and supportedfeature. Instances must be created withSSLContext methodswrap_socket() andwrap_bio().(Contributed by Christian Heimes inbpo-32951)

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

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

string

string.Template now lets you to optionally modify the regularexpression pattern for braced placeholders and non-braced placeholdersseparately. (Contributed by Barry Warsaw inbpo-1198569.)

subprocess

Thesubprocess.run() function accepts the newcapture_outputkeyword argument. When true, stdout and stderr will be captured.This is equivalent to passingsubprocess.PIPE asstdout andstderr arguments.(Contributed by Bo Bayles inbpo-32102.)

Thesubprocess.run function and thesubprocess.Popen constructornow accept thetext keyword argument as an aliastouniversal_newlines.(Contributed by Andrew Clegg inbpo-31756.)

On Windows the default forclose_fds was changed fromFalse toTrue when redirecting the standard handles. It's now possible to setclose_fds to true when redirecting the standard handles. Seesubprocess.Popen. This means thatclose_fds now defaults toTrue on all supported platforms.(Contributed by Segev Finer inbpo-19764.)

The subprocess module is now more graceful when handlingKeyboardInterrupt duringsubprocess.call(),subprocess.run(), or in aPopencontext manager. It now waits a short amount of time for the childto exit, before continuing the handling of theKeyboardInterruptexception.(Contributed by Gregory P. Smith inbpo-25942.)

sys

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

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

The newsys.get_coroutine_origin_tracking_depth() function returnsthe current coroutine origin tracking depth, as set bythe newsys.set_coroutine_origin_tracking_depth().asynciohas been converted to use this new API instead ofthe deprecatedsys.set_coroutine_wrapper().(Contributed by Nathaniel J. Smith inbpo-32591.)

time

PEP 564 adds six new functions with nanosecond resolution to thetime module:

New clock identifiers have been added:

  • time.CLOCK_BOOTTIME (Linux): Identical totime.CLOCK_MONOTONIC, except it also includes any time that thesystem is suspended.

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

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

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

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

tkinter

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

tracemalloc

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

types

The newWrapperDescriptorType,MethodWrapperType,MethodDescriptorType,andClassMethodDescriptorType classes 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 entriesdynamically as specified byPEP 560.(Contributed by Ivan Levkivskyi inbpo-32717.)

unicodedata

The internalunicodedata database has been upgraded to useUnicode 11. (Contributed by BenjaminPeterson.)

unittest

The new-k command-line option allows filtering tests by a namesubstring or a Unix shell-like pattern.For example,python-munittest-kfoo runsfoo_tests.SomeTest.test_something,bar_tests.SomeTest.test_foo,but notbar_tests.FooTest.test_something.(Contributed by Jonas Haag inbpo-32071.)

unittest.mock

Thesentinel attributes now preserve their identitywhen they arecopied orpickled. (Contributed bySerhiy Storchaka inbpo-20804.)

The newseal() function allows sealingMock instances, which will disallow further creationof attribute mocks. The seal is applied recursively to all attributes thatare themselves mocks.(Contributed by Mario Corchero inbpo-30541.)

urllib.parse

urllib.parse.quote() has been updated fromRFC 2396 toRFC 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 optionalbacktickkeyword argument. When it's true, zeros are represented by'`'instead of spaces. (Contributed by Xiang Zhang inbpo-30103.)

uuid

The newUUID.is_safe attribute relays informationfrom the platform about whether generated UUIDs are generated with amultiprocessing-safe method.(Contributed by Barry Warsaw inbpo-22807.)

uuid.getnode() now prefers universally administeredMAC addresses over locally administered MAC addresses.This makes a better guarantee for global uniqueness of UUIDs returnedfromuuid.uuid1(). If only locally administered MAC addresses areavailable, 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-band the new CPython-specific-Xdev option) are always passedto the warnings machinery via thesys.warnoptions attribute.

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

    • theBytesWarning filter for-b (or-bb)

    • any filters specified with the-W option

    • any filters specified with thePYTHONWARNINGS environmentvariable

    • any other CPython specific filters (e.g. thedefault filter addedfor the new-Xdev mode)

    • any implicit filters defined directly by the warnings machinery

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

(由 Nick Coghlan 和 Victor Stinner 在bpo-20361bpo-32043bpo-32230 中貢獻。)

Deprecation warnings are once again shown by default in single-file scripts andat 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, thexml.dom.minidom andxml.sax modules no longer processexternal entities by default.(Contributed by Christian Heimes ingh-61441.)

xml.etree

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

xmlrpc.server

SimpleXMLRPCDispatcher.register_functioncan now be used as a decorator. (Contributed by Xiang Zhang inbpo-7769.)

zipapp

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

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

zipfile

ZipFile now accepts the newcompresslevel parameter tocontrol the compression level.(Contributed by Bo Bayles inbpo-21417.)

Subdirectories in archives created byZipFile are now stored inalphabetical order.(Contributed by Bernhard M. Wiedemann inbpo-30693.)

C API 變更

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

The newcontext variables functionalityexposes a number ofnew C APIs.

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

The newPy_RETURN_RICHCOMPARE macro eases writing richcomparison functions.(Contributed by Petr Victorin inbpo-23699.)

The newPy_UNREACHABLE macro can be used to mark unreachablecode paths.(Contributed by Barry Warsaw inbpo-31338.)

Thetracemalloc now exposes a C API through the newPyTraceMalloc_Track() andPyTraceMalloc_Untrack()functions.(Contributed by Victor Stinner inbpo-30054.)

The newimport__find__load__start() andimport__find__load__done() static markers can be used to tracemodule imports.(Contributed by Christian Heimes inbpo-31574.)

The fieldsname anddoc of structuresPyMemberDef,PyGetSetDef,PyStructSequence_Field,PyStructSequence_Desc,andwrapperbase are now of typeconstchar* rather ofchar*. (Contributed by Serhiy Storchaka inbpo-28761.)

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

The result ofPyMapping_Keys(),PyMapping_Values() andPyMapping_Items() is now always a list, rather than a list or atuple. (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 functionsPyOS_BeforeFork(),PyOS_AfterFork_Parent() andPyOS_AfterFork_Child(). (Contributed by Antoine Pitrou inbpo-16500.)

ThePyExc_RecursionErrorInst singleton that was part of the public APIhas been removed as its members being never cleared may cause a segfaultduring finalization of the interpreter. Contributed by Xavier de Gaye inbpo-22898 andbpo-30697.

Added C API support for timezones with timezone constructorsPyTimeZone_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() andPyThread_get_thread_ident(), and theid parameter ofPyThreadState_SetAsyncExc() changed fromlong tounsignedlong.(Contributed by Serhiy Storchaka inbpo-6532.)

PyUnicode_AsWideCharString() now raises aValueError if thesecond argument isNULL and thewchar_t* string contains nullcharacters. (Contributed by Serhiy Storchaka inbpo-30708.)

Changes to the startup sequence and the management of dynamic memoryallocators mean that the long documented requirement to callPy_Initialize() before calling most C API functions is nowrelied on more heavily, and failing to abide by it may lead to segfaults inembedding applications. See the移植至 Python 3.7 section in thisdocument and thePython 初始化之前 section in the C API documentationfor more details.

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

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

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

Thestart andend parameters ofPyUnicode_FindChar() arenow adjusted to behave like string slices.(Contributed by Xiang Zhang inbpo-28822.)

建置變更

Support for building--without-threads has been removed. Thethreading module is now always available.(Contributed by Antoine Pitrou inbpo-31370.).

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

The Windows build process no longer depends on Subversion to pull in externalsources, 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 todownload a copy of 32-bit Python for this purpose. (Contributed by ZacharyWare inbpo-30450.)

Thessl module 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 longersupported. LibreSSL is temporarily not supported as well. LibreSSL releasesup to version 2.6.4 are missing required OpenSSL 1.0.2 APIs.

最佳化

The overhead of calling many methods of various standard library classesimplemented in C has been significantly reduced by porting more codeto use theMETH_FASTCALL convention.(Contributed by Victor Stinner inbpo-29300,bpo-29507,bpo-29452, andbpo-29286.)

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

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

Theasyncio module received a number of notable optimizations forcommonly used functions:

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

sorted() andlist.sort() have been optimized for common casesto 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 whenname is not found andobj does 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 tomake 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 to30% faster in the common case.(Contributed by Paul Ganssle inbpo-32403.)

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

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

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

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

Themodify() methods of classesselectors.EpollSelector,selectors.PollSelectorandselectors.DevpollSelector may be around 10% faster underheavy loads. (Contributed by Giampaolo Rodola' inbpo-30014)

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

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

Significant speed improvements to alternate constructors fordatetime.date anddatetime.datetime by using fast-pathconstructors when not constructing subclasses. (Contributed by Paul Ganssleinbpo-32403)

The speed of comparison ofarray.array instances has beenimproved considerably in certain cases. It is now from 10x to 70x fasterwhen 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 theline and opt into receivingtheopcode events from the interpreter by setting the corresponding newf_trace_lines andf_trace_opcodes attributes on theframe 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__.origin is also set toNone(previously the string"namespace"). Seebpo-32305. Also, thenamespace module object's__spec__.loader is set to the same value as__loader__ (previously, the former was set toNone). Seebpo-32303.

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

  • Thedistutilsupload command no longer tries to change CRend-of-line characters to CRLF. This fixes a corruption issue with sdiststhat ended with a byte equivalent to CR.(Contributed by Bo Bayles inbpo-32304.)

Deprecated Python Behavior

Yield expressions (bothyield andyieldfrom clauses) are now deprecatedin comprehensions and generator expressions (aside from the iterable expressionin the leftmostfor clause). This ensures that comprehensionsalways immediately return a container of the appropriate type (rather thanpotentially returning agenerator iterator object), while generatorexpressions won't attempt to interleave their implicit output with the outputfrom any explicit yield expressions. In Python 3.7, such expressions emitDeprecationWarning when compiled, in Python 3.8 this will be aSyntaxError.(Contributed by Serhiy Storchaka inbpo-10544.)

Returning a subclass ofcomplex fromobject.__complex__() isdeprecated and will be an error in future Python versions. This makes__complex__() consistent withobject.__int__() andobject.__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.Lock andother asyncio synchronization primitives has been deprecated. Anasynchronous context manager must be used in order to acquire and releasethe 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.abc will nolonger be exposed in the regularcollections module. This will helpcreate a clearer distinction between the concrete classes and the abstractbase classes.(Contributed by Serhiy Storchaka inbpo-25988.)

dbm

dbm.dumb now supports reading read-only files and no longer writes theindex file when it is not changed. A deprecation warning is now emittedif 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 inEnumclasses will raise aTypeError (e.g.1inColor); similarly,attempting to check for non-Flag objects in aFlag member willraiseTypeError (e.g.1inPerm.RW); currently, both operationsreturnFalse instead.(Contributed by Ethan Furman inbpo-33217.)

gettext

Using non-integer value for selecting a plural form ingettext isnow deprecated. It never correctly worked. (Contributed by Serhiy Storchakainbpo-28692.)

importlib

MethodsMetaPathFinder.find_module()(replaced byMetaPathFinder.find_spec())andPathEntryFinder.find_loader()(replaced byPathEntryFinder.find_spec())both deprecated in Python 3.4 now emitDeprecationWarning.(Contributed by Matthias Bussonnier inbpo-29576.)

Theimportlib.abc.ResourceLoader ABC has been deprecated infavour ofimportlib.abc.ResourceReader.

locale

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

macpath

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

threading

dummy_threading and_dummy_thread have been deprecated. It isno longer possible to build Python with threading disabled.Usethreading instead.(Contributed by Antoine Pitrou inbpo-31370.)

socket

The silent argument value truncation insocket.htons() andsocket.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. Usessl.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() andsys.get_coroutine_wrapper().

The undocumentedsys.callstats() function has been deprecated andwill 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 witha macro ifPy_LIMITED_API is not set or set to a value in the rangebetween0x03050400 and0x03060000 (not inclusive), or is0x03060100or 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 platformsare now expected to provide at least one ofC.UTF-8 (full locale),C.utf8 (full locale) orUTF-8 (LC_CTYPE-only locale) as analternative to the legacyASCII-basedC locale.

  • OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython3.7 with SSL/TLS support on older platforms still using these versionsrequires 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 bydefault.

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

    CPython's ownCI configuration file provides anexample of using the SSLcompatibility testing infrastructure inCPython's test suite to build and link against OpenSSL 1.1.0 rather than anoutdated system provided OpenSSL.

API 與功能的移除

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

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

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

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

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

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

  • Functionsbool(),float(),list() andtuple() nolonger take keyword arguments. The first argument ofint() can nowbe passed only as positional argument.

  • Removed previously deprecated in Python 2.4 classesPlist,Dict and_InternalDict in theplistlib module. Dict values in the resultof functionsreadPlist() andreadPlistFromBytes() are now normal dicts. You no longercan use attribute access to access items of these dictionaries.

  • Theasyncio.windows_utils.socketpair() function has beenremoved. Use thesocket.socketpair() function instead,it is available on all platforms since Python 3.5.asyncio.windows_utils.socketpair was just an alias tosocket.socketpair on Python 3.5 and newer.

  • asyncio no longer exports theselectors and_overlapped modules asasyncio.selectors andasyncio._overlapped. Replacefromasyncioimportselectors withimportselectors.

  • Direct instantiation ofssl.SSLSocket andssl.SSLObjectobjects is now prohibited. The constructors were never documented, tested,or designed as public constructors. Users were supposed to usessl.wrap_socket() orssl.SSLContext.(Contributed by Christian Heimes inbpo-32951.)

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

Module Removals

Thefpectl module has been removed. It was never enabled bydefault, never worked correctly on x86-64, and it changed the PythonABI 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 specifierswithouthaving to specify a minor version as well. Sopy-3-32 andpy-3-64become valid as well aspy-3.7-32, also the -m-64 and -m.n-64 formsare now accepted to force 64 bit python even if 32 bit would have otherwisebeen 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-0 to produce a list of the installed pythons,with default marked with an asterisk. Runningpy-0p will include the paths.If py is run with a version specifier that cannot be matched it will also printtheshort form list of available specifiers.(Contributed by Steve Barnes inbpo-30362.)

移植至 Python 3.7

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

Python 行為的改變

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

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

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

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

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

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

  • When using the-m switch, the initial working directory is now addedtosys.path, rather than an empty string (which dynamically denotedthe current working directory at the time of each import). Any programs thatare checking for the empty string, or otherwise relying on the previousbehaviour, will need to be updated accordingly (e.g. by also checking foros.getcwd() oros.path.dirname(__main__.__file__), depending on whythe code was checking for the empty string in the first place).

Python API 的變更

  • socketserver.ThreadingMixIn.server_close() now waits until allnon-daemon threads complete. Set the newsocketserver.ThreadingMixIn.block_on_close class attribute toFalse to get the pre-3.7 behaviour.(Contributed by Victor Stinner inbpo-31233 andbpo-33540.)

  • socketserver.ForkingMixIn.server_close() now waits until allchild processes complete. Set the newsocketserver.ForkingMixIn.block_on_close class attribute toFalseto get the pre-3.7 behaviour.(Contributed by Victor Stinner inbpo-31151 andbpo-33540.)

  • Thelocale.localeconv() function now temporarily sets theLC_CTYPElocale to the value ofLC_NUMERIC in some cases.(Contributed by Victor Stinner inbpo-31900.)

  • pkgutil.walk_packages() now raises aValueError ifpath isa 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. (Contributedby Serhiy Storchaka inbpo-29193.)

  • Attributeskey,value andcoded_value of classhttp.cookies.Morsel are now read-only.Assigning to them was deprecated in Python 3.5.Use theset() method for setting them.(Contributed by Serhiy Storchaka inbpo-29192.)

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

  • Thestruct.Struct.format type is nowstr instead ofbytes. (Contributed by Victor Stinner inbpo-21071.)

  • cgi.parse_multipart() now accepts theencoding anderrorsarguments and returns the same results asFieldStorage: for non-file fields, the value associated to a keyis a list of strings, not bytes.(Contributed by Pierre Quentel inbpo-29979.)

  • Due to internal changes insocket, callingsocket.fromshare()on a socket created bysocket.share in olderPython versions is not supported.

  • repr forBaseException has changed to not include the trailingcomma. Most exceptions are affected by this change.(Contributed by Serhiy Storchaka inbpo-30399.)

  • repr fordatetime.timedelta has changed to include the keywordarguments in the output. (Contributed by Utkarsh Upadhyay inbpo-30302.)

  • Becauseshutil.rmtree() is now implemented using theos.scandir()function, the user specified handleronerror is now called with the firstargumentos.scandir instead ofos.listdir when listing the directoryis failed.

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

  • The result of splitting a string on aregularexpressionthat could match an empty string has been changed. For examplesplitting onr'\s*' will now split not only on whitespaces as itdid previously, but also on empty strings before all non-whitespacecharacters and just before the end of the string.The previous behavior can be restored by changing the patterntor'\s+'. AFutureWarning was emitted for such patterns sincePython 3.5.

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

    re.sub() now replaces empty matches adjacent to a previousnon-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').

    (由 Serhiy Storchaka 在bpo-25054bpo-32308 中貢獻。)

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

  • tracemalloc.Traceback frames are now sorted from oldest to mostrecent to be more consistent withtraceback.(Contributed by Jesse Bakker inbpo-32121.)

  • On OSes that supportsocket.SOCK_NONBLOCK orsocket.SOCK_CLOEXEC bit flags, thesocket.type no longer has them applied.Therefore, checks likeifsock.type==socket.SOCK_STREAMwork as expected on all platforms.(Contributed by Yury Selivanov inbpo-32331.)

  • On Windows the default for theclose_fds argument ofsubprocess.Popen was changed fromFalse toTruewhen redirecting the standard handles. If you previously depended on handlesbeing inherited when usingsubprocess.Popen with standard ioredirection, you will have to passclose_fds=False to preserve theprevious behaviour, or useSTARTUPINFO.lpAttributeList.

  • importlib.machinery.PathFinder.invalidate_caches() -- which implicitlyaffectsimportlib.invalidate_caches() -- now deletes entriesinsys.path_importer_cache which 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 theirdocumentation. Previously, these methods returnedasyncio.Futureinstances.(Contributed by Yury Selivanov inbpo-32327.)

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

  • Struct.format is now astr instanceinstead of abytes instance.(Contributed by Victor Stinner inbpo-21071.)

  • argparse subparsers can now be made mandatory by passingrequired=TruetoArgumentParser.add_subparsers().(Contributed by Anthony Sottile inbpo-26510.)

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

  • Calendar.itermonthdateswill now consistently raise an exception when a date falls outside of the0001-01-01 through9999-12-31 range. To support applications thatcannot tolerate such exceptions, the newCalendar.itermonthdays3 andCalendar.itermonthdays4 can be used.The new methods return tuples and are not restricted by the range supported bydatetime.date.(Contributed by Alexander Belopolsky inbpo-28292.)

  • collections.ChainMap now preserves the order of the underlyingmappings. (Contributed by Raymond Hettinger inbpo-32792.)

  • Thesubmit() method ofconcurrent.futures.ThreadPoolExecutorandconcurrent.futures.ProcessPoolExecutor now raisesaRuntimeError if called during interpreter shutdown.(Contributed by Mark Nemec inbpo-33097.)

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

  • Several undocumented internal imports were removed.One example is thatos.errno is no longer available; useimporterrnodirectly instead.Note that such undocumented internal imports may be removed any time withoutnotice, even in micro version releases.

C API 中的改動

The functionPySlice_GetIndicesEx() is considered unsafe forresizable sequences. If the slice indices are not instances ofint,but objects that implement the__index__() method, the sequence can beresized after passing its length toPySlice_GetIndicesEx(). Thiscan lead to returning indices out of the length of the sequence. Foravoiding possible problems use new functionsPySlice_Unpack() andPySlice_AdjustIndices().(Contributed by Serhiy Storchaka inbpo-27867.)

CPython 位元組碼變更

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

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

Windows-only Changes

The file used to overridesys.path is now called<python-executable>._pth instead of'sys.path'.See找尋模組 for more information.(Contributed by Steve Dower inbpo-28137.)

Other CPython implementation changes

In preparation for potential future changes to the public CPython runtimeinitialization API (seePEP 432 for an initial, but somewhat outdated,draft), CPython's internal startupand configuration management logic has been significantly refactored. Whilethese updates are intended to be entirely transparent to both embeddingapplications and users of the regular CPython CLI, they're being mentionedhere as the refactoring changes the internal order of various operationsduring 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 ofbpo-22257, and further updated by Nick, Eric, and Victor Stinner in anumber of other issues). Some known details affected:

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

  • warnings filters added by an embedding application withPySys_AddWarnOption() should now more consistently take precedenceover the default filters set by the interpreter

Due to changes in the way the default warnings filters are configured,settingPy_BytesWarningFlag to a value greater than one is no longersufficient to both emitBytesWarning messages and have them convertedto exceptions. Instead, the flag must be set (to cause the warnings to beemitted in the first place), and an expliciterror::BytesWarningwarnings filter added to convert them to exceptions.

Due to a change in the way docstrings are handled by the compiler, theimplicitreturnNone in a function body consisting solely of a docstringis now marked as occurring on the same line as the docstring, not on thefunction'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 byhaving swap exception state when entering or exiting a generator.(Contributed by Mark Shannon inbpo-25612.)

Python 3.7.1 中顯著的變更

Starting in 3.7.1,Py_Initialize() now consistently reads and respectsall of the same environment settings asPy_Main() (in earlier Pythonversions, 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). Ifthis behavior is unwanted, setPy_IgnoreEnvironmentFlag to 1 beforecallingPy_Initialize().

In 3.7.1 the C API for Context Variableswas updated to usePyObject pointers. See alsobpo-34762.

In 3.7.1 thetokenize module now implicitly emits aNEWLINE tokenwhen provided with input that does not have a trailing new line. This behaviornow matches what the C tokenizer does internally.(Contributed by Ammar Askar inbpo-33899.)

Python 3.7.2 中顯著的變更

In 3.7.2,venv on Windows no longer copies the original binaries, butcreates redirector scripts namedpython.exe andpythonw.exe instead.This resolves a long standing issue where all virtual environments would haveto be upgraded or recreated with each Python update. However, note that thisrelease will still require recreation of virtual environments in order to getthe new scripts.

Python 3.7.6 中顯著的變更

Due to significant security concerns, thereuse_address parameter ofasyncio.loop.create_datagram_endpoint() is no longer supported. This isbecause of the behavior of the socket optionSO_REUSEADDR in UDP. For moredetails, see the documentation forloop.create_datagram_endpoint().(Contributed by Kyle Stanley, Antoine Pitrou, and Yury Selivanov inbpo-37228.)

Python 3.7.10 中顯著的變更

Earlier Python versions allowed using both; and& asquery parameter separators inurllib.parse.parse_qs() andurllib.parse.parse_qsl(). Due to security concerns, and to conform withnewer W3C recommendations, this has been changed to allow only a singleseparator key, with& as the default. This change also affectscgi.parse() andcgi.parse_multipart() as they use the affectedfunctions internally. For more details, please see their respectivedocumentation.(Contributed by Adam Goldschmidt, Senthil Kumaran and Ken Jin inbpo-42967.)

Python 3.7.11 中顯著的變更

A security fix alters theftplib.FTP behavior to not trust theIPv4 address sent from the remote server when setting up a passive datachannel. We reuse the ftp server IP address instead. For unusual coderequiring the old behavior, set atrust_server_pasv_ipv4_addressattribute on your FTP instance toTrue. (Seegh-87451)

The presence of newline or tab characters in parts of a URL allows for someforms of attacks. Following the WHATWG specification that updates RFC 3986,ASCII newline\n,\r and tab\t characters are stripped from theURL by the parserurllib.parse() preventing such attacks. The removalcharacters are controlled by a new module level variableurllib.parse._UNSAFE_URL_BYTES_TO_REMOVE. (Seegh-88048)

Notable security feature in 3.7.14

Converting betweenint andstr in bases other than 2(binary), 4, 8 (octal), 16 (hexadecimal), or 32 such as base 10 (decimal)now raises aValueError if the number of digits in string form isabove a limit to avoid potential denial of service attacks due to thealgorithmic complexity. This is a mitigation forCVE 2020-10735.This limit can be configured or disabled by environment variable, commandline flag, orsys APIs. See theinteger string conversionlength limitation documentation. The default limitis 4300 digits in string form.