Python 3.6 有什麼新功能

編輯者:

Elvis Pranskevichus <elvis@magic.io>, Yury Selivanov <yury@magic.io>

本文介紹了 Python 3.6 與 3.5 相比多了哪些新功能。Python 3.6 已於 2016 年 12 月 23 日發布。完整詳情請見changelog

也參考

PEP 494 - Python 3.6 發佈時程

發布重點摘要

新增語法特性:

  • PEP 498, formatted string literals.

  • PEP 515, underscores in numeric literals.

  • PEP 526, syntax for variable annotations.

  • PEP 525, asynchronous generators.

  • PEP 530: asynchronous comprehensions.

新的函式庫模組:

CPython 實作改進:

標準函式庫中的顯著改進

  • Theasyncio module has received new features, significantusability and performance improvements, and a fair amount of bug fixes.Starting with Python 3.6 theasyncio module is no longer provisionaland its API is considered stable.

  • A newfile system path protocol has beenimplemented to supportpath-like objects.All standard library functions operating on paths have been updated towork with the new protocol.

  • Thedatetime module has gained support forLocal Time Disambiguation.

  • Thetyping module received a number ofimprovements.

  • Thetracemalloc module has been significantly reworkedand is now used to provide better output forResourceWarningas well as provide better diagnostics for memory allocation errors.See thePYTHONMALLOC section for moreinformation.

安全性改進:

  • The newsecrets module has been added to simplify the generation ofcryptographically strong pseudo-random numbers suitable formanaging secrets such as account authentication, tokens, and similar.

  • On Linux,os.urandom() now blocks until the system urandom entropypool is initialized to increase the security. See thePEP 524 for therationale.

  • Thehashlib andssl modules now support OpenSSL 1.1.0.

  • The default settings and feature set of thessl module have beenimproved.

  • Thehashlib module received support for the BLAKE2, SHA-3 and SHAKEhash algorithms and thescrypt() key derivation function.

Windows improvements:

  • PEP 528 andPEP 529,Windows filesystem and console encoding changed to UTF-8.

  • Thepy.exe launcher, when used interactively, no longer prefersPython 2 over Python 3 when the user doesn't specify a version (viacommand line arguments or a config file). Handling of shebang linesremains unchanged - "python" refers to Python 2 in that case.

  • python.exe andpythonw.exe have been marked as long-path aware,which means that the 260 character path limit may no longer apply.Seeremoving the MAX_PATH limitation for details.

  • A._pth file can be added to force isolated mode and fully specifyall search paths to avoid registry and environment lookup. Seethe documentation for more information.

  • Apython36.zip file now works as a landmark to inferPYTHONHOME. Seethe documentation formore information.

新增功能

PEP 498: Formatted string literals

PEP 498 introduces a new kind of string literals:f-strings, orformatted string literals.

Formatted string literals are prefixed with'f' and are similar tothe format strings accepted bystr.format(). They contain replacementfields surrounded by curly braces. The replacement fields are expressions,which are evaluated at run time, and then formatted using theformat() protocol:

>>>name="Fred">>>f"He said his name is{name}."'He said his name is Fred.'>>>width=10>>>precision=4>>>value=decimal.Decimal("12.34567")>>>f"result:{value:{width}.{precision}}"# nested fields'result:      12.35'

也參考

PEP 498 -- Literal String Interpolation.

由 Eric V. Smith 撰寫 PEP 與實作。

Feature documentation.

PEP 526: Syntax for variable annotations

PEP 484 introduced the standard for type annotations of functionparameters, a.k.a. type hints. This PEP adds syntax to Python for annotatingthe types of variables including class variables and instance variables:

primes:List[int]=[]captain:str# Note: no initial value!classStarship:stats:Dict[str,int]={}

Just as for function annotations, the Python interpreter does not attach anyparticular meaning to variable annotations and only stores them in the__annotations__ attribute of a class or module.

In contrast to variable declarations in statically typed languages,the goal of annotation syntax is to provide an easy way to specify structuredtype metadata for third party tools and libraries via the abstract syntax treeand the__annotations__ attribute.

也參考

PEP 526 -- Syntax for variable annotations.

PEP written by Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach,and Guido van Rossum. Implemented by Ivan Levkivskyi.

Tools that use or will use the new syntax:mypy,pytype, PyCharm, etc.

PEP 515: Underscores in Numeric Literals

PEP 515 adds the ability to use underscores in numeric literals forimproved readability. For example:

>>>1_000_000_000_000_0001000000000000000>>>0x_FF_FF_FF_FF4294967295

Single underscores are allowed between digits and after any basespecifier. Leading, trailing, or multiple underscores in a row are notallowed.

Thestring formatting language also now has supportfor the'_' option to signal the use of an underscore for a thousandsseparator for floating-point presentation types and for integerpresentation type'd'. For integer presentation types'b','o','x', and'X', underscores will be inserted every 4digits:

>>>'{:_}'.format(1000000)'1_000_000'>>>'{:_x}'.format(0xFFFFFFFF)'ffff_ffff'

也參考

PEP 515 -- Underscores in Numeric Literals

由 Georg Brandl 與 Serhiy Storchaka 撰寫 PEP。

PEP 525: Asynchronous Generators

PEP 492 introduced support for native coroutines andasync /awaitsyntax to Python 3.5. A notable limitation of the Python 3.5 implementationis that it was not possible to useawait andyield in the samefunction body. In Python 3.6 this restriction has been lifted, making itpossible to defineasynchronous generators:

asyncdefticker(delay,to):"""Yield numbers from 0 to *to* every *delay* seconds."""foriinrange(to):yieldiawaitasyncio.sleep(delay)

The new syntax allows for faster and more concise code.

也參考

PEP 525 -- Asynchronous Generators

由 Yury Selivanov 撰寫 PEP 與實作。

PEP 530: Asynchronous Comprehensions

PEP 530 adds support for usingasyncfor in list, set, dictcomprehensions and generator expressions:

result=[iasyncforiinaiter()ifi%2]

Additionally,await expressions are supported in all kindsof comprehensions:

result=[awaitfun()forfuninfuncsifawaitcondition()]

也參考

PEP 530 -- Asynchronous Comprehensions

由 Yury Selivanov 撰寫 PEP 與實作。

PEP 487: Simpler customization of class creation

It is now possible to customize subclass creation without using a metaclass.The new__init_subclass__ classmethod will be called on the base classwhenever a new subclass is created:

classPluginBase:subclasses=[]def__init_subclass__(cls,**kwargs):super().__init_subclass__(**kwargs)cls.subclasses.append(cls)classPlugin1(PluginBase):passclassPlugin2(PluginBase):pass

In order to allow zero-argumentsuper() calls to work correctly from__init_subclass__() implementations, custom metaclasses mustensure that the new__classcell__ namespace entry is propagated totype.__new__ (as described inCreating the class object).

也參考

PEP 487 -- Simpler customization of class creation

由 Martin Teichmann 撰寫 PEP 與實作。

Feature documentation

PEP 487: Descriptor Protocol Enhancements

PEP 487 extends the descriptor protocol to include the new optional__set_name__() method. Whenever a new class is defined, the newmethod will be called on all descriptors included in the definition, providingthem with a reference to the class being defined and the name given to thedescriptor within the class namespace. In other words, instances ofdescriptors can now know the attribute name of the descriptor in theowner class:

classIntField:def__get__(self,instance,owner):returninstance.__dict__[self.name]def__set__(self,instance,value):ifnotisinstance(value,int):raiseValueError(f'expecting integer in{self.name}')instance.__dict__[self.name]=value# this is the new initializer:def__set_name__(self,owner,name):self.name=nameclassModel:int_field=IntField()

也參考

PEP 487 -- Simpler customization of class creation

由 Martin Teichmann 撰寫 PEP 與實作。

Feature documentation

PEP 519: Adding a file system path protocol

File system paths have historically been represented asstrorbytes objects. This has led to people who write code whichoperate on file system paths to assume that such objects are only oneof those two types (anint representing a file descriptordoes not count as that is not a file path). Unfortunately thatassumption prevents alternative object representations of file systempaths likepathlib from working with pre-existing code,including Python's standard library.

To fix this situation, a new interface represented byos.PathLike has been defined. By implementing the__fspath__() method, an object signals that itrepresents a path. An object can then provide a low-levelrepresentation of a file system path as astr orbytes object. This means an object is consideredpath-like if it implementsos.PathLike or is astr orbytes objectwhich represents a file system path. Code can useos.fspath(),os.fsdecode(), oros.fsencode() to explicitly get astr and/orbytes representation of a path-likeobject.

The built-inopen() function has been updated to acceptos.PathLike objects, as have all relevant functions in theos andos.path modules, and most other functions andclasses in the standard library. Theos.DirEntry classand relevant classes inpathlib have also been updated toimplementos.PathLike.

The hope is that updating the fundamental functions for operatingon file system paths will lead to third-party code to implicitlysupport allpath-like objects without anycode changes, or at least very minimal ones (e.g. callingos.fspath() at the beginning of code before operating on apath-like object).

Here are some examples of how the new interface allows forpathlib.Path to be used more easily and transparently withpre-existing code:

>>>importpathlib>>>withopen(pathlib.Path("README"))asf:...contents=f.read()...>>>importos.path>>>os.path.splitext(pathlib.Path("some_file.txt"))('some_file', '.txt')>>>os.path.join("/a/b",pathlib.Path("c"))'/a/b/c'>>>importos>>>os.fspath(pathlib.Path("some_file.txt"))'some_file.txt'

(Implemented by Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra.)

也參考

PEP 519 -- Adding a file system path protocol

由 Brett Cannon 與 Koos Zevenhoven 撰寫 PEP。

PEP 495: Local Time Disambiguation

In most world locations, there have been and will be times when local clocksare moved back. In those times, intervals are introduced in which localclocks show the same time twice in the same day. In these situations, theinformation displayed on a local clock (or stored in a Python datetimeinstance) is insufficient to identify a particular moment in time.

PEP 495 adds the newfold attribute to instances ofdatetime.datetime anddatetime.time classes to differentiatebetween two moments in time for which local times are the same:

>>>u0=datetime(2016,11,6,4,tzinfo=timezone.utc)>>>foriinrange(4):...u=u0+i*HOUR...t=u.astimezone(Eastern)...print(u.time(),'UTC =',t.time(),t.tzname(),t.fold)...04:00:00 UTC = 00:00:00 EDT 005:00:00 UTC = 01:00:00 EDT 006:00:00 UTC = 01:00:00 EST 107:00:00 UTC = 02:00:00 EST 0

The values of thefold attribute have thevalue0 for all instances except those that represent the second(chronologically) moment in time in an ambiguous case.

也參考

PEP 495 -- Local Time Disambiguation

PEP written by Alexander Belopolsky and Tim Peters, implementationby Alexander Belopolsky.

PEP 529: Change Windows filesystem encoding to UTF-8

Representing filesystem paths is best performed with str (Unicode) rather thanbytes. However, there are some situations where using bytes is sufficient andcorrect.

Prior to Python 3.6, data loss could result when using bytes paths on Windows.With this change, using bytes to represent paths is now supported on Windows,provided those bytes are encoded with the encoding returned bysys.getfilesystemencoding(), which now defaults to'utf-8'.

Applications that do not use str to represent paths should useos.fsencode() andos.fsdecode() to ensure their bytes arecorrectly encoded. To revert to the previous behaviour, setPYTHONLEGACYWINDOWSFSENCODING or callsys._enablelegacywindowsfsencoding().

SeePEP 529 for more information and discussion of code modifications thatmay be required.

PEP 528: Change Windows console encoding to UTF-8

The default console on Windows will now accept all Unicode characters andprovide correctly read str objects to Python code.sys.stdin,sys.stdout andsys.stderr now default to utf-8 encoding.

This change only applies when using an interactive console, and not whenredirecting files or pipes. To revert to the previous behaviour for interactiveconsole use, setPYTHONLEGACYWINDOWSSTDIO.

也參考

PEP 528 -- Change Windows console encoding to UTF-8

由 Steve Dower 撰寫 PEP 與實作。

PEP 520: Preserving Class Attribute Definition Order

Attributes in a class definition body have a natural ordering: the sameorder in which the names appear in the source. This order is nowpreserved in the new class's__dict__ attribute.

Also, the effective default classexecution namespace (returned fromtype.__prepare__()) is now an insertion-order-preservingmapping.

也參考

PEP 520 -- Preserving Class Attribute Definition Order

由 Eric Snow 撰寫 PEP 與實作。

PEP 468: Preserving Keyword Argument Order

**kwargs in a function signature is now guaranteed to be aninsertion-order-preserving mapping.

也參考

PEP 468 -- Preserving Keyword Argument Order

由 Eric Snow 撰寫 PEP 與實作。

Newdict implementation

Thedict type now uses a "compact" representationbased ona proposal by Raymond Hettingerwhich wasfirst implemented by PyPy.The memory usage of the newdict() is between 20% and 25% smallercompared to Python 3.5.

The order-preserving aspect of this new implementation is considered animplementation detail and should not be relied upon (this may change inthe future, but it is desired to have this new dict implementation inthe language for a few releases before changing the language spec to mandateorder-preserving semantics for all current and future Pythonimplementations; this also helps preserve backwards-compatibilitywith older versions of the language where random iteration order isstill in effect, e.g. Python 3.5).

(Contributed by INADA Naoki inbpo-27350. Ideaoriginally suggested by Raymond Hettinger.)

PEP 523: Adding a frame evaluation API to CPython

While Python provides extensive support to customize how codeexecutes, one place it has not done so is in the evaluation of frameobjects. If you wanted some way to intercept frame evaluation inPython there really wasn't any way without directly manipulatingfunction pointers for defined functions.

PEP 523 changes this by providing an API to make frameevaluation pluggable at the C level. This will allow for tools suchas debuggers and JITs to intercept frame evaluation before theexecution of Python code begins. This enables the use of alternativeevaluation implementations for Python code, tracking frameevaluation, etc.

This API is not part of the limited C API and is marked as private tosignal that usage of this API is expected to be limited and onlyapplicable to very select, low-level use-cases. Semantics of theAPI will change with Python as necessary.

也參考

PEP 523 -- Adding a frame evaluation API to CPython

由 Brett Cannon 與 Dino Viehland 撰寫 PEP。

PYTHONMALLOC environment variable

The newPYTHONMALLOC environment variable allows setting the Pythonmemory allocators and installing debug hooks.

It is now possible to install debug hooks on Python memory allocators on Pythoncompiled in release mode usingPYTHONMALLOC=debug. Effects of debug hooks:

  • Newly allocated memory is filled with the byte0xCB

  • Freed memory is filled with the byte0xDB

  • Detect violations of the Python memory allocator API. For example,PyObject_Free() called on a memory block allocated byPyMem_Malloc().

  • Detect writes before the start of a buffer (buffer underflows)

  • Detect writes after the end of a buffer (buffer overflows)

  • Check that theGIL is held when allocatorfunctions ofPYMEM_DOMAIN_OBJ (ex:PyObject_Malloc()) andPYMEM_DOMAIN_MEM (ex:PyMem_Malloc()) domains are called.

Checking if the GIL is held is also a new feature of Python 3.6.

See thePyMem_SetupDebugHooks() function for debug hooks on Pythonmemory allocators.

It is now also possible to force the usage of themalloc() allocator ofthe C library for all Python memory allocations usingPYTHONMALLOC=malloc.This is helpful when using external memory debuggers like Valgrind ona Python compiled in release mode.

On error, the debug hooks on Python memory allocators now use thetracemalloc module to get the traceback where a memory block wasallocated.

Example of fatal error on buffer overflow usingpython3.6-Xtracemalloc=5 (store 5 frames in traces):

Debugmemoryblockataddressp=0x7fbcd41666f8:API'o'4bytesoriginallyrequestedThe7padbytesatp-7areFORBIDDENBYTE,asexpected.The8padbytesattail=0x7fbcd41666fcarenotallFORBIDDENBYTE(0xfb):attail+0:0x02***OUCHattail+1:0xfbattail+2:0xfbattail+3:0xfbattail+4:0xfbattail+5:0xfbattail+6:0xfbattail+7:0xfbTheblockwasmadebycall#1233329 to debug malloc/realloc.Dataatp:1a2b3000Memoryblockallocatedat(mostrecentcallfirst):File"test/test_bytes.py",line323File"unittest/case.py",line600File"unittest/case.py",line648File"unittest/suite.py",line122File"unittest/suite.py",line84FatalPythonerror:badtrailingpadbyteCurrentthread0x00007fbcdbd32700(mostrecentcallfirst):File"test/test_bytes.py",line323intest_hexFile"unittest/case.py",line600inrunFile"unittest/case.py",line648in__call__File"unittest/suite.py",line122inrunFile"unittest/suite.py",line84in__call__File"unittest/suite.py",line122inrunFile"unittest/suite.py",line84in__call__...

(由 Victor Stinner 於bpo-26516bpo-26564 中貢獻。)

DTrace and SystemTap probing support

Python can now be built--with-dtrace which enables static markersfor the following events in the interpreter:

  • function call/return

  • garbage collection started/finished

  • line of code executed.

This can be used to instrument running interpreters in production,without the need to recompile specificdebug builds orproviding application-specific profiling/debugging code.

More details in使用 DTrace 和 SystemTap 檢測 CPython.

The current implementation is tested on Linux and macOS. Additionalmarkers may be added in the future.

(Contributed by Łukasz Langa inbpo-21590, based on patches byJesús Cea Avión, David Malcolm, and Nikhil Benesch.)

其他語言更動

Some smaller changes made to the core Python language are:

  • Aglobal ornonlocal statement must now textually appearbefore the first use of the affected name in the same scope.Previously this was aSyntaxWarning.

  • It is now possible to set aspecial method toNone to indicate that the corresponding operation is not available.For example, if a class sets__iter__() toNone, the classis not iterable.(Contributed by Andrew Barnert and Ivan Levkivskyi inbpo-25958.)

  • Long sequences of repeated traceback lines are now abbreviated as"[Previouslinerepeated{count}moretimes]" (seetraceback for an example).(Contributed by Emanuel Barry inbpo-26823.)

  • Import now raises the new exceptionModuleNotFoundError(subclass ofImportError) when it cannot find a module. Codethat currently checks for ImportError (in try-except) will still work.(Contributed by Eric Snow inbpo-15767.)

  • Class methods relying on zero-argumentsuper() will now work correctlywhen called from metaclass methods during class creation.(Contributed by Martin Teichmann inbpo-23722.)

新模組

secrets

The main purpose of the newsecrets module is to provide an obvious wayto reliably generate cryptographically strong pseudo-random values suitablefor managing secrets, such as account authentication, tokens, and similar.

警告

Note that the pseudo-random generators in therandom moduleshouldNOT be used for security purposes. Usesecretson Python 3.6+ andos.urandom() on Python 3.5 and earlier.

也參考

PEP 506 -- Adding A Secrets Module To The Standard Library

由 Steven D'Aprano 撰寫 PEP 與實作。

改進的模組

array

Exhausted iterators ofarray.array will now stay exhausted evenif the iterated array is extended. This is consistent with the behaviorof other mutable sequences.

由 Serhiy Storchaka 於bpo-26492 中貢獻。

ast

The newast.Constant AST node has been added. It can be usedby external AST optimizers for the purposes of constant folding.

由 Victor Stinner 於bpo-26146 中貢獻。

asyncio

Starting with Python 3.6 theasyncio module is no longer provisional and itsAPI is considered stable.

Notable changes in theasyncio module since Python 3.5.0(all backported to 3.5.x due to the provisional status):

binascii

Theb2a_base64() function now accepts an optionalnewlinekeyword argument to control whether the newline character is appended to thereturn value.(Contributed by Victor Stinner inbpo-25357.)

cmath

The newcmath.tau (τ) constant has been added.(Contributed by Lisa Roach inbpo-12345, seePEP 628 for details.)

New constants:cmath.inf andcmath.nan tomatchmath.inf andmath.nan, and alsocmath.infjandcmath.nanj to match the format used by complex repr.(Contributed by Mark Dickinson inbpo-23229.)

collections

The newCollection abstract base class has beenadded to represent sized iterable container classes.(Contributed by Ivan Levkivskyi, docs by Neil Girdhar inbpo-27598.)

The newReversible abstract base class representsiterable classes that also provide the__reversed__() method.(Contributed by Ivan Levkivskyi inbpo-25987.)

The newAsyncGenerator abstract base class representsasynchronous generators.(Contributed by Yury Selivanov inbpo-28720.)

Thenamedtuple() function now accepts an optionalkeyword argumentmodule, which, when specified, is used forthe__module__ attribute of the returned named tuple class.(Contributed by Raymond Hettinger inbpo-17941.)

Theverbose andrename arguments fornamedtuple() are now keyword-only.(Contributed by Raymond Hettinger inbpo-25628.)

Recursivecollections.deque instances can now be pickled.(Contributed by Serhiy Storchaka inbpo-26482.)

concurrent.futures

TheThreadPoolExecutorclass constructor now accepts an optionalthread_name_prefix argumentto make it possible to customize the names of the threads created by thepool.(Contributed by Gregory P. Smith inbpo-27664.)

contextlib

Thecontextlib.AbstractContextManager class has been added toprovide an abstract base class for context managers. It provides asensible default implementation for__enter__() which returnsself and leaves__exit__() an abstract method. A matchingclass has been added to thetyping module astyping.ContextManager.(Contributed by Brett Cannon inbpo-25609.)

datetime

Thedatetime andtime classes havethe newfold attribute used to disambiguate local timewhen necessary. Many functions in thedatetime have beenupdated to support local time disambiguation.SeeLocal Time Disambiguation section for moreinformation.(Contributed by Alexander Belopolsky inbpo-24773.)

Thedatetime.strftime() anddate.strftime() methods now supportISO 8601 date directives%G,%u and%V.(Contributed by Ashley Anderson inbpo-12006.)

Thedatetime.isoformat() functionnow accepts an optionaltimespec argument that specifies the numberof additional components of the time value to include.(Contributed by Alessandro Cucci and Alexander Belopolsky inbpo-19475.)

Thedatetime.combine() nowaccepts an optionaltzinfo argument.(Contributed by Alexander Belopolsky inbpo-27661.)

decimal

NewDecimal.as_integer_ratio()method that returns a pair(n,d) of integers that represent the givenDecimal instance as a fraction, in lowest terms andwith a positive denominator:

>>>Decimal('-3.14').as_integer_ratio()(-157, 50)

(由 Stefan Krah 和 Mark Dickinson 於bpo-25928 中貢獻。)

distutils

Thedefault_format attribute has been removed fromdistutils.command.sdist.sdist and theformatsattribute defaults to['gztar']. Although not anticipated,any code relying on the presence ofdefault_format mayneed to be adapted. Seebpo-27819 for more details.

email

The new email API, enabled via thepolicy keyword to various constructors, isno longer provisional. Theemail documentation has been reorganized andrewritten to focus on the new API, while retaining the old documentation forthe legacy API. (Contributed by R. David Murray inbpo-24277.)

Theemail.mime classes now all accept an optionalpolicy keyword.(Contributed by Berker Peksag inbpo-27331.)

TheDecodedGenerator now supports thepolicykeyword.

There is a newpolicy attribute,message_factory, that controls what class is usedby default when the parser creates new message objects. For theemail.policy.compat32 policy this isMessage,for the new policies it isEmailMessage.(Contributed by R. David Murray inbpo-20476.)

encodings

On Windows, added the'oem' encoding to useCP_OEMCP, and the'ansi'alias for the existing'mbcs' encoding, which uses theCP_ACP code page.(Contributed by Steve Dower inbpo-27959.)

enum

Two new enumeration base classes have been added to theenum module:Flag andIntFlags. Both are used to defineconstants that can be combined using the bitwise operators.(Contributed by Ethan Furman inbpo-23591.)

Many standard library modules have been updated to use theIntFlags class for their constants.

The newenum.auto value can be used to assign values to enummembers automatically:

>>>fromenumimportEnum,auto>>>classColor(Enum):...red=auto()...blue=auto()...green=auto()...>>>list(Color)[<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]

faulthandler

On Windows, thefaulthandler module now installs a handler for Windowsexceptions: seefaulthandler.enable(). (Contributed by Victor Stinner inbpo-23848.)

fileinput

hook_encoded() now supports theerrors argument.(Contributed by Joseph Hackman inbpo-25788.)

hashlib

hashlib supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2.(Contributed by Christian Heimes inbpo-26470.)

BLAKE2 hash functions were added to the module.blake2b()andblake2s() are always available and support the fullfeature set of BLAKE2.(Contributed by Christian Heimes inbpo-26798 based on code byDmitry Chestnykh and Samuel Neves. Documentation written by Dmitry Chestnykh.)

The SHA-3 hash functionssha3_224(),sha3_256(),sha3_384(),sha3_512(), and SHAKE hash functionsshake_128() andshake_256() were added.(Contributed by Christian Heimes inbpo-16113. Keccak Code Packageby Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, andRonny Van Keer.)

The password-based key derivation functionscrypt() is nowavailable with OpenSSL 1.1.0 and newer.(Contributed by Christian Heimes inbpo-27928.)

http.client

HTTPConnection.request() andendheaders() both now supportchunked encoding request bodies.(Contributed by Demian Brecht and Rolf Krahl inbpo-12319.)

idlelib and IDLE

The idlelib package is being modernized and refactored to make IDLE look andwork better and to make the code easier to understand, test, and improve. Partof making IDLE look better, especially on Linux and Mac, is using ttk widgets,mostly in the dialogs. As a result, IDLE no longer runs with tcl/tk 8.4. Itnow requires tcl/tk 8.5 or 8.6. We recommend running the latest release ofeither.

'Modernizing' includes renaming and consolidation of idlelib modules. Therenaming of files with partial uppercase names is similar to the renaming of,for instance, Tkinter and TkFont to tkinter and tkinter.font in 3.0. As aresult, imports of idlelib files that worked in 3.5 will usually not work in3.6. At least a module name change will be needed (see idlelib/README.txt),sometimes more. (Name changes contributed by Al Swiegart and Terry Reedy inbpo-24225. Most idlelib patches since have been and will be part of theprocess.)

In compensation, the eventual result with be that some idlelib classes will beeasier to use, with better APIs and docstrings explaining them. Additionaluseful information will be added to idlelib when available.

New in 3.6.2:

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

New in 3.6.3:

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 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.)

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.)

New in 3.6.4:

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.)

New in 3.6.6:

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.6.7:

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.)

importlib

Import now raises the new exceptionModuleNotFoundError(subclass ofImportError) when it cannot find a module. Codethat current checks forImportError (in try-except) will still work.(Contributed by Eric Snow inbpo-15767.)

importlib.util.LazyLoader now callscreate_module() on the wrapped loader, removing therestriction thatimportlib.machinery.BuiltinImporter andimportlib.machinery.ExtensionFileLoader couldn't be used withimportlib.util.LazyLoader.

importlib.util.cache_from_source(),importlib.util.source_from_cache(), andimportlib.util.spec_from_file_location() now accept apath-like object.

inspect

Theinspect.signature() function now reports theimplicit.0 parameters generated by the compiler for comprehension andgenerator expression scopes as if they were positional-only parameters calledimplicit0. (Contributed by Jelle Zijlstra inbpo-19611.)

To reduce code churn when upgrading from Python 2.7 and the legacyinspect.getargspec() API, the previously documented deprecation ofinspect.getfullargspec() has been reversed. While this function isconvenient for single/source Python 2/3 code bases, the richerinspect.signature() interface remains the recommended approach for newcode. (Contributed by Nick Coghlan inbpo-27172)

json

json.load() andjson.loads() now support binary input. EncodedJSON should be represented using either UTF-8, UTF-16, or UTF-32.(Contributed by Serhiy Storchaka inbpo-17909.)

logging

The newWatchedFileHandler.reopenIfNeeded()method has been added to add the ability to check if the log file needs tobe reopened.(Contributed by Marian Horban inbpo-24884.)

math

The tau (τ) constant has been added to themath andcmathmodules.(Contributed by Lisa Roach inbpo-12345, seePEP 628 for details.)

multiprocessing

Proxy Objects returned bymultiprocessing.Manager() can now be nested.(Contributed by Davin Potts inbpo-6766.)

os

See the summary ofPEP 519 for details on how theos andos.path modules now supportpath-like objects.

scandir() now supportsbytes paths on Windows.

A newclose() method allows explicitly closing ascandir() iterator. Thescandir() iterator nowsupports thecontext manager protocol. If ascandir()iterator is neither exhausted nor explicitly closed aResourceWarningwill be emitted in its destructor.(Contributed by Serhiy Storchaka inbpo-25994.)

On Linux,os.urandom() now blocks until the system urandom entropy poolis initialized to increase the security. See thePEP 524 for the rationale.

The Linuxgetrandom() syscall (get random bytes) is now exposed as the newos.getrandom() function.(Contributed by Victor Stinner, part of thePEP 524)

pathlib

pathlib now supportspath-like objects.(Contributed by Brett Cannon inbpo-27186.)

細節請見PEP 519 中的摘要。

pdb

ThePdb class constructor has a new optionalreadrc argumentto control whether.pdbrc files should be read.

pickle

Objects that need__new__ called with keyword arguments can now be pickledusingpickle protocols older than protocol version 4.Protocol version 4 already supports this case. (Contributed by SerhiyStorchaka inbpo-24164.)

pickletools

pickletools.dis() now outputs the implicit memo index for theMEMOIZE opcode.(Contributed by Serhiy Storchaka inbpo-25382.)

pydoc

Thepydoc module has learned to respect theMANPAGERenvironment variable.(Contributed by Matthias Klose inbpo-8637.)

help() andpydoc can now list named tuple fields in theorder they were defined rather than alphabetically.(Contributed by Raymond Hettinger inbpo-24879.)

random

The newchoices() function returns a list of elements ofspecified size from the given population with optional weights.(Contributed by Raymond Hettinger inbpo-18844.)

re

Added support of modifier spans in regular expressions. Examples:'(?i:p)ython' matches'python' and'Python', but not'PYTHON';'(?i)g(?-i:v)r' matches'GvR' and'gvr', but not'GVR'.(Contributed by Serhiy Storchaka inbpo-433028.)

Match object groups can be accessed by__getitem__, which isequivalent togroup(). Somo['name'] is now equivalent tomo.group('name'). (Contributed by Eric Smith inbpo-24454.)

Match objects now supportindex-likeobjects as groupindices.(Contributed by Jeroen Demeyer and Xiang Zhang inbpo-27177.)

readline

Addedset_auto_history() to enable or disableautomatic addition of input to the history list. (Contributed byTyler Crompton inbpo-26870.)

rlcompleter

Private and special attribute names now are omitted unless the prefix startswith underscores. A space or a colon is added after some completed keywords.(Contributed by Serhiy Storchaka inbpo-25011 andbpo-25209.)

shlex

Theshlex has muchimproved shell compatibilitythrough the newpunctuation_chars argument to control which charactersare treated as punctuation.(Contributed by Vinay Sajip inbpo-1521950.)

site

When specifying paths to add tosys.path in a.pth file,you may now specify file paths on top of directories (e.g. zip files).(Contributed by Wolfgang Langner inbpo-26587).

sqlite3

sqlite3.Cursor.lastrowid now supports theREPLACE statement.(Contributed by Alex LordThorsen inbpo-16864.)

socket

Theioctl() function now supports theSIO_LOOPBACK_FAST_PATH control code.(Contributed by Daniel Stokes inbpo-26536.)

Thegetsockopt() constantsSO_DOMAIN,SO_PROTOCOL,SO_PEERSEC, andSO_PASSSEC are now supported.(Contributed by Christian Heimes inbpo-26907.)

Thesetsockopt() now supports thesetsockopt(level,optname,None,optlen:int) form.(Contributed by Christian Heimes inbpo-27744.)

The socket module now supports the address familyAF_ALG to interface with Linux Kernel crypto API.ALG_*,SOL_ALG andsendmsg_afalg() were added.(Contributed by Christian Heimes inbpo-27744 with support fromVictor Stinner.)

New Linux constantsTCP_USER_TIMEOUT andTCP_CONGESTION were added.(Contributed by Omar Sandoval,bpo-26273).

socketserver

Servers based on thesocketserver module, including thosedefined inhttp.server,xmlrpc.server andwsgiref.simple_server, now support thecontext managerprotocol.(Contributed by Aviv Palivoda inbpo-26404.)

Thewfile attribute ofStreamRequestHandler classes now implementstheio.BufferedIOBase writable interface. In particular,callingwrite() is now guaranteed to send thedata in full. (Contributed by Martin Panter inbpo-26721.)

ssl

ssl supports OpenSSL 1.1.0. The minimum recommend version is 1.0.2.(Contributed by Christian Heimes inbpo-26470.)

3DES has been removed from the default cipher suites and ChaCha20 Poly1305cipher suites have been added.(Contributed by Christian Heimes inbpo-27850 andbpo-27766.)

SSLContext has better default configuration for optionsand ciphers.(Contributed by Christian Heimes inbpo-28043.)

SSL session can be copied from one client-side connection to anotherwith the newSSLSession class. TLS session resumption canspeed up the initial handshake, reduce latency and improve performance(Contributed by Christian Heimes inbpo-19500 based on a draft byAlex Warhawk.)

The newget_ciphers() method can be used toget a list of enabled ciphers in order of cipher priority.

All constants and flags have been converted toIntEnum andIntFlags.(Contributed by Christian Heimes inbpo-28025.)

Server and client-side specific TLS protocols forSSLContextwere added.(Contributed by Christian Heimes inbpo-28085.)

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.)

statistics

A newharmonic_mean() function has been added.(Contributed by Steven D'Aprano inbpo-27181.)

struct

struct now supports IEEE 754 half-precision floats via the'e'format specifier.(Contributed by Eli Stevens, Mark Dickinson inbpo-11734.)

subprocess

subprocess.Popen destructor now emits aResourceWarning warningif the child process is still running. Use the context manager protocol (withproc:...) or explicitly call thewait() method toread the exit status of the child process. (Contributed by Victor Stinner inbpo-26741.)

Thesubprocess.Popen constructor and all functions that pass argumentsthrough to it now acceptencoding anderrors arguments. Specifying eitherof these will enable text mode for thestdin,stdout andstderr streams.(Contributed by Steve Dower inbpo-6135.)

sys

The newgetfilesystemencodeerrors() function returns the name ofthe error mode used to convert between Unicode filenames and bytes filenames.(Contributed by Steve Dower inbpo-27781.)

On Windows the return value of thegetwindowsversion() functionnow includes theplatform_version field which contains the accurate majorversion, minor version and build number of the current operating system,rather than the version that is being emulated for the process(Contributed by Steve Dower inbpo-27932.)

telnetlib

telnetlib.Telnet is now a context manager (contributed byStéphane Wirtel inbpo-25485).

time

Thestruct_time attributestm_gmtoff andtm_zone are now available on all platforms.

timeit

The newTimer.autorange() conveniencemethod has been added to callTimer.timeit()repeatedly so that the total run time is greater or equal to 200 milliseconds.(Contributed by Steven D'Aprano inbpo-6422.)

timeit now warns when there is substantial (4x) variancebetween best and worst times.(Contributed by Serhiy Storchaka inbpo-23552.)

tkinter

Added methodstrace_add(),trace_remove() andtrace_info()in thetkinter.Variable class. They replace old methodstrace_variable(),trace(),trace_vdelete() andtrace_vinfo() that use obsolete Tcl commands and mightnot work in future versions of Tcl.(Contributed by Serhiy Storchaka inbpo-22115).

traceback

Both the traceback module and the interpreter's builtin exception display nowabbreviate long sequences of repeated lines in tracebacks as shown in thefollowing example:

>>>deff():f()...>>>f()Traceback (most recent call last):  File"<stdin>", line1, in<module>  File"<stdin>", line1, inf  File"<stdin>", line1, inf  File"<stdin>", line1, inf  [Previous line repeated 995 more times]RecursionError:maximum recursion depth exceeded

(由 Emanuel Barry 於bpo-26823 中貢獻。)

tracemalloc

Thetracemalloc module now supports tracing memory allocations inmultiple different address spaces.

The newDomainFilter filter class has been addedto filter block traces by their address space (domain).

(由 Victor Stinner 於bpo-26588 中貢獻。)

typing

Since thetyping module isprovisional,all changes introduced in Python 3.6 have also beenbackported to Python 3.5.x.

Thetyping module has a much improved support for generic typealiases. For exampleDict[str,Tuple[S,T]] is now a validtype annotation.(Contributed by Guido van Rossum inGithub #195.)

Thetyping.ContextManager class has been added forrepresentingcontextlib.AbstractContextManager.(Contributed by Brett Cannon inbpo-25609.)

Thetyping.Collection class has been added forrepresentingcollections.abc.Collection.(Contributed by Ivan Levkivskyi inbpo-27598.)

Thetyping.ClassVar type construct has been added tomark class variables. As introduced inPEP 526, a variable annotationwrapped in ClassVar indicates that a given attribute is intended to be used asa class variable and should not be set on instances of that class.(Contributed by Ivan Levkivskyi inGithub #280.)

A newTYPE_CHECKING constant that is assumed to beTrue by the static type checkers, but isFalse at runtime.(Contributed by Guido van Rossum inGithub #230.)

A newNewType() helper function has been added to createlightweight distinct types for annotations:

fromtypingimportNewTypeUserId=NewType('UserId',int)some_id=UserId(524313)

The static type checker will treat the new type as if it were a subclassof the original type. (Contributed by Ivan Levkivskyi inGithub #189.)

unicodedata

Theunicodedata module now uses data fromUnicode 9.0.0.(Contributed by Benjamin Peterson.)

unittest.mock

TheMock class has the following improvements:

urllib.request

If a HTTP request has a file or iterable body (other than abytes object) but noContent-Length header, rather thanthrowing an error,AbstractHTTPHandler nowfalls back to use chunked transfer encoding.(Contributed by Demian Brecht and Rolf Krahl inbpo-12319.)

urllib.robotparser

RobotFileParser now supports theCrawl-delay andRequest-rate extensions.(Contributed by Nikolay Bogoychev inbpo-16099.)

venv

venv accepts a new parameter--prompt. This parameter provides analternative prefix for the virtual environment. (Proposed by Łukasz Balcerzakand ported to 3.6 by Stéphane Wirtel inbpo-22829.)

warnings

A new optionalsource parameter has been added to thewarnings.warn_explicit() function: the destroyed object which emitted aResourceWarning. Asource attribute has also been added towarnings.WarningMessage (contributed by Victor Stinner inbpo-26568 andbpo-26567).

When aResourceWarning warning is logged, thetracemalloc module is nowused to try to retrieve the traceback where the destroyed object was allocated.

Example with the scriptexample.py:

importwarningsdeffunc():returnopen(__file__)f=func()f=None

Output of the commandpython3.6-Wd-Xtracemalloc=5example.py:

example.py:7:ResourceWarning:unclosedfile<_io.TextIOWrappername='example.py'mode='r'encoding='UTF-8'>f=NoneObjectallocatedat(mostrecentcallfirst):File"example.py",lineno4returnopen(__file__)File"example.py",lineno6f=func()

The "Object allocated at" traceback is new and is only displayed iftracemalloc is tracing Python memory allocations and if thewarnings module was already imported.

winreg

Added the 64-bit integer typeREG_QWORD.(Contributed by Clement Rouault inbpo-23026.)

winsound

Allowed keyword arguments to be passed toBeep,MessageBeep, andPlaySound (bpo-27982).

xmlrpc.client

Thexmlrpc.client module now supports unmarshallingadditional data types used by the Apache XML-RPC implementationfor numerics andNone.(Contributed by Serhiy Storchaka inbpo-26885.)

zipfile

A newZipInfo.from_file() class methodallows making aZipInfo instance from a filesystem file.A newZipInfo.is_dir() method can be usedto check if theZipInfo instance represents a directory.(Contributed by Thomas Kluyver inbpo-26039.)

TheZipFile.open() method can now be used towrite data into a ZIP file, as well as for extracting data.(Contributed by Thomas Kluyver inbpo-26039.)

zlib

Thecompress() anddecompress() functions now acceptkeyword arguments.(Contributed by Aviv Palivoda inbpo-26243 andXiang Zhang inbpo-16764 respectively.)

最佳化

  • The Python interpreter now uses a 16-bit wordcode instead of bytecode whichmade a number of opcode optimizations possible.(Contributed by Demur Rumed with input and reviews fromSerhiy Storchaka and Victor Stinner inbpo-26647 andbpo-28050.)

  • Theasyncio.Future class now has an optimized C implementation.(Contributed by Yury Selivanov and INADA Naoki inbpo-26081.)

  • Theasyncio.Task class now has an optimizedC implementation. (Contributed by Yury Selivanov inbpo-28544.)

  • Various implementation improvements in thetyping module(such as caching of generic types) allow up to 30 times performanceimprovements and reduced memory footprint.

  • The ASCII decoder is now up to 60 times as fast for error handlerssurrogateescape,ignore andreplace (Contributedby Victor Stinner inbpo-24870).

  • The ASCII and the Latin1 encoders are now up to 3 times as fast for theerror handlersurrogateescape(Contributed by Victor Stinner inbpo-25227).

  • The UTF-8 encoder is now up to 75 times as fast for error handlersignore,replace,surrogateescape,surrogatepass (Contributedby Victor Stinner inbpo-25267).

  • The UTF-8 decoder is now up to 15 times as fast for error handlersignore,replace andsurrogateescape (Contributedby Victor Stinner inbpo-25301).

  • bytes%args is now up to 2 times faster. (Contributed by Victor Stinnerinbpo-25349).

  • bytearray%args is now between 2.5 and 5 times faster. (Contributed byVictor Stinner inbpo-25399).

  • Optimizebytes.fromhex() andbytearray.fromhex(): they are nowbetween 2x and 3.5x faster. (Contributed by Victor Stinner inbpo-25401).

  • Optimizebytes.replace(b'',b'.') andbytearray.replace(b'',b'.'):up to 80% faster. (Contributed by Josh Snider inbpo-26574).

  • Allocator functions of thePyMem_Malloc() domain(PYMEM_DOMAIN_MEM) now use thepymalloc memory allocator instead ofmalloc() function of the C library. Thepymalloc allocator is optimized for objects smaller or equal to 512 byteswith a short lifetime, and usemalloc() for larger memory blocks.(Contributed by Victor Stinner inbpo-26249).

  • pickle.load() andpickle.loads() are now up to 10% faster whendeserializing many small objects (Contributed by Victor Stinner inbpo-27056).

  • Passingkeyword arguments to a function has anoverhead in comparison with passingpositional arguments. Now in extension functions implemented with usingArgument Clinic this overhead is significantly decreased.(Contributed by Serhiy Storchaka inbpo-27574).

  • Optimizedglob() andiglob() functions in theglob module; they are now about 3--6 times faster.(Contributed by Serhiy Storchaka inbpo-25596).

  • Optimized globbing inpathlib by usingos.scandir();it is now about 1.5--4 times faster.(Contributed by Serhiy Storchaka inbpo-26032).

  • xml.etree.ElementTree parsing, iteration and deepcopy performancehas been significantly improved.(Contributed by Serhiy Storchaka inbpo-25638,bpo-25873,andbpo-25869.)

  • Creation offractions.Fraction instances from floats anddecimals is now 2 to 3 times faster.(Contributed by Serhiy Storchaka inbpo-25971.)

建置和 C API 變更

其他改進

  • When--version (short form:-V) is supplied twice,Python printssys.version for detailed information.

    $./python-VVPython 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]

已棄用

新關鍵字

async andawait are not recommended to be used as variable, class,function or module names. Introduced byPEP 492 in Python 3.5, they willbecome proper keywords in Python 3.7. Starting in Python 3.6, the use ofasync orawait as names will generate aDeprecationWarning.

Deprecated Python behavior

Raising theStopIteration exception inside a generator will nowgenerate aDeprecationWarning, and will trigger aRuntimeErrorin Python 3.7. SeePEP 479: Change StopIteration handling inside generators for details.

The__aiter__() method is now expected to return an asynchronousiterator directly instead of returning an awaitable as previously.Doing the former will trigger aDeprecationWarning. Backwardcompatibility will be removed in Python 3.7.(Contributed by Yury Selivanov inbpo-27243.)

A backslash-character pair that is not a valid escape sequence now generatesaDeprecationWarning. Although this will eventually become aSyntaxError, that will not be for several Python releases.(Contributed by Emanuel Barry inbpo-27364.)

When performing a relative import, falling back on__name__ and__path__ from the calling module when__spec__ or__package__ are not defined now raises anImportWarning.(Contributed by Rose Ames inbpo-25791.)

Deprecated Python modules, functions and methods

asynchat

Theasynchat has been deprecated in favor ofasyncio.(Contributed by Mariatta inbpo-25002.)

asyncore

Theasyncore has been deprecated in favor ofasyncio.(Contributed by Mariatta inbpo-25002.)

dbm

Unlike otherdbm implementations, thedbm.dumb modulecreates databases with the'rw' mode and allows modifying the databaseopened with the'r' mode. This behavior is now deprecated and willbe removed in 3.8.(Contributed by Serhiy Storchaka inbpo-21708.)

distutils

The undocumentedextra_path argument to thedistutils.Distribution constructor is now considered deprecatedand will raise a warning if set. Support for this parameter will beremoved in a future Python release. Seebpo-27919 for details.

grp

The support of non-integer arguments ingetgrgid() has beendeprecated.(Contributed by Serhiy Storchaka inbpo-26129.)

importlib

Theimportlib.machinery.SourceFileLoader.load_module() andimportlib.machinery.SourcelessFileLoader.load_module() methodsare now deprecated. They were the only remaining implementations ofimportlib.abc.Loader.load_module() inimportlib that had notbeen deprecated in previous versions of Python in favour ofimportlib.abc.Loader.exec_module().

Theimportlib.machinery.WindowsRegistryFinder class is nowdeprecated. As of 3.6.0, it is still added tosys.meta_path bydefault (on Windows), but this may change in future releases.

os

Undocumented support of generalbytes-like objectsas paths inos functions,compile() and similar functions isnow deprecated.(Contributed by Serhiy Storchaka inbpo-25791 andbpo-26754.)

re

Support for inline flags(?letters) in the middle of the regularexpression has been deprecated and will be removed in a future Pythonversion. Flags at the start of a regular expression are still allowed.(Contributed by Serhiy Storchaka inbpo-22493.)

ssl

OpenSSL 0.9.8, 1.0.0 and 1.0.1 are deprecated and no longer supported.In the future thessl module will require at least OpenSSL 1.0.2 or1.1.0.

SSL-related arguments likecertfile,keyfile andcheck_hostnameinftplib,http.client,imaplib,poplib,andsmtplib have been deprecated in favor ofcontext.(Contributed by Christian Heimes inbpo-28022.)

A couple of protocols and functions of thessl module are nowdeprecated. Some features will no longer be available in future versionsof OpenSSL. Other features are deprecated in favor of a different API.(Contributed by Christian Heimes inbpo-28022 andbpo-26470.)

tkinter

Thetkinter.tix module is now deprecated.tkinter usersshould usetkinter.ttk instead.

venv

Thepyvenv script has been deprecated in favour ofpython3-mvenv.This prevents confusion as to what Python interpreterpyvenv isconnected to and thus what Python interpreter will be used by the virtualenvironment. (Contributed by Brett Cannon inbpo-25154.)

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.)

Deprecated functions and types of the C API

Undocumented functionsPyUnicode_AsEncodedObject(),PyUnicode_AsDecodedObject(),PyUnicode_AsEncodedUnicode()andPyUnicode_AsDecodedUnicode() are deprecated now.Use thegeneric codec based API instead.

Deprecated Build Options

The--with-system-ffi configure flag is now on by default on non-macOSUNIX platforms. It may be disabled by using--without-system-ffi, butusing the flag is deprecated and will not be accepted in Python 3.7.macOS is unaffected by this change. Note that many OS distributors alreadyuse the--with-system-ffi flag when building their system Python.

已移除

API 與功能的移除

  • Unknown escapes consisting of'\' and an ASCII letter inregular expressions will now cause an error. In replacement templates forre.sub() they are still allowed, but deprecated.There.LOCALE flag can now only be used with binary patterns.

  • inspect.getmoduleinfo() was removed (was deprecated since CPython 3.3).inspect.getmodulename() should be used for obtaining the modulename for a given path.(Contributed by Yury Selivanov inbpo-13248.)

  • traceback.Ignore class andtraceback.usage,traceback.modname,traceback.fullmodname,traceback.find_lines_from_code,traceback.find_lines,traceback.find_strings,traceback.find_executable_lines methods were removed from thetraceback module. They were undocumented methods deprecated sincePython 3.2 and equivalent functionality is available from private methods.

  • Thetk_menuBar() andtk_bindForTraversal() dummy methods intkinter widget classes were removed (corresponding Tk commandswere obsolete since Tk 4.0).

  • Theopen() method of thezipfile.ZipFileclass no longer supports the'U' mode (was deprecated since Python 3.4).Useio.TextIOWrapper for reading compressed text files inuniversal newlines mode.

  • The undocumentedIN,CDROM,DLFCN,TYPES,CDIO, andSTROPTS modules have been removed. They had been available in theplatform specificLib/plat-*/ directories, but were chronically out ofdate, inconsistently available across platforms, and unmaintained. Thescript that created these modules is still available in the sourcedistribution atTools/scripts/h2py.py.

  • The deprecatedasynchat.fifo class has been removed.

移植至 Python 3.6

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

Changes in 'python' Command Behavior

  • The output of a special Python build with definedCOUNT_ALLOCS,SHOW_ALLOC_COUNT orSHOW_TRACK_COUNT macros is now off bydefault. It can be re-enabled using the-Xshowalloccount option.It now outputs tostderr instead ofstdout.(Contributed by Serhiy Storchaka inbpo-23034.)

Python API 的變更

  • open() will no longer allow combining the'U' mode flagwith'+'.(Contributed by Jeff Balogh and John O'Connor inbpo-2091.)

  • sqlite3 no longer implicitly commits an open transaction before DDLstatements.

  • On Linux,os.urandom() now blocks until the system urandom entropy poolis initialized to increase the security.

  • Whenimportlib.abc.Loader.exec_module() is defined,importlib.abc.Loader.create_module() must also be defined.

  • PyErr_SetImportError() now setsTypeError when itsmsgargument is not set. Previously onlyNULL was returned.

  • The format of theco_lnotab attribute of code objectschanged to supporta negative line number delta. By default, Python does not emit bytecode witha negative line number delta. Functions usingframe.f_lineno,PyFrame_GetLineNumber() orPyCode_Addr2Line() are not affected.Functions directly decodingco_lnotab should be updated to use a signed8-bit integer type for the line number delta, but this is only required tosupport applications using a negative line number delta. SeeObjects/lnotab_notes.txt for theco_lnotab format and how to decodeit, and see thePEP 511 for the rationale.

  • The functions in thecompileall module now return booleans insteadof1 or0 to represent success or failure, respectively. Thanks tobooleans being a subclass of integers, this should only be an issue if youwere doing identity checks for1 or0. Seebpo-25768.

  • Reading theport attribute ofurllib.parse.urlsplit() andurlparse() resultsnow raisesValueError for out-of-range values, rather thanreturningNone. Seebpo-20059.

  • Theimp module now raises aDeprecationWarning instead ofPendingDeprecationWarning.

  • The following modules have had missing APIs added to their__all__attributes to match the documented APIs:calendar,cgi,csv,ElementTree,enum,fileinput,ftplib,logging,mailbox,mimetypes,optparse,plistlib,smtpd,subprocess,tarfile,threading andwave. This means they will export new symbols whenimport*is used.(Contributed by Joel Taddei and Jacek Kołodziej inbpo-23883.)

  • When performing a relative import, if__package__ does not compare equalto__spec__.parent thenImportWarning is raised.(Contributed by Brett Cannon inbpo-25791.)

  • When a relative import is performed and no parent package is known, thenImportError will be raised. Previously,SystemError could beraised. (Contributed by Brett Cannon inbpo-18018.)

  • Servers based on thesocketserver module, including thosedefined inhttp.server,xmlrpc.server andwsgiref.simple_server, now only catch exceptions derivedfromException. Therefore if a request handler raisesan exception likeSystemExit orKeyboardInterrupt,handle_error() is no longer called, andthe exception will stop a single-threaded server. (Contributed byMartin Panter inbpo-23430.)

  • spwd.getspnam() now raises aPermissionError instead ofKeyError if the user doesn't have privileges.

  • Thesocket.socket.close() method now raises an exception ifan error (e.g.EBADF) was reported by the underlying system call.(Contributed by Martin Panter inbpo-26685.)

  • Thedecode_data argument for thesmtpd.SMTPChannel andsmtpd.SMTPServer constructors is nowFalse by default.This means that the argument passed toprocess_message() is now a bytes object bydefault, andprocess_message() will be passed keyword arguments.Code that has already been updated in accordance with the deprecationwarning generated by 3.5 will not be affected.

  • All optional arguments of thedump(),dumps(),load() andloads() functions andJSONEncoder andJSONDecoder classconstructors in thejson module are nowkeyword-only.(Contributed by Serhiy Storchaka inbpo-18726.)

  • Subclasses oftype which don't overridetype.__new__ may nolonger use the one-argument form to get the type of an object.

  • As part ofPEP 487, the handling of keyword arguments passed totype (other than the metaclass hint,metaclass) is nowconsistently delegated toobject.__init_subclass__(). This means thattype.__new__() andtype.__init__() both now accept arbitrarykeyword arguments, butobject.__init_subclass__() (which is called fromtype.__new__()) will reject them by default. Custom metaclassesaccepting additional keyword arguments will need to adjust their calls totype.__new__() (whether direct or viasuper) accordingly.

  • Indistutils.command.sdist.sdist, thedefault_formatattribute has been removed and is no longer honored. Instead, thegzipped tarfile format is the default on all platforms and noplatform-specific selection is made.In environments where distributions arebuilt on Windows and zip distributions are required, configurethe project with asetup.cfg file containing the following:

    [sdist]formats=zip

    This behavior has also been backported to earlier Python versionsby Setuptools 26.0.0.

  • In theurllib.request module and thehttp.client.HTTPConnection.request() method, if no Content-Lengthheader field has been specified and the request body is a file object,it is now sent with HTTP 1.1 chunked encoding. If a file object has tobe sent to a HTTP 1.0 server, the Content-Length value now has to bespecified by the caller.(Contributed by Demian Brecht and Rolf Krahl with tweaks fromMartin Panter inbpo-12319.)

  • TheDictReader now returns rows of typeOrderedDict.(Contributed by Steve Holden inbpo-27842.)

  • Thecrypt.METHOD_CRYPT will no longer be added tocrypt.methodsif unsupported by the platform.(Contributed by Victor Stinner inbpo-25287.)

  • Theverbose andrename arguments fornamedtuple() are now keyword-only.(Contributed by Raymond Hettinger inbpo-25628.)

  • On Linux,ctypes.util.find_library() now looks inLD_LIBRARY_PATH for shared libraries.(Contributed by Vinay Sajip inbpo-9998.)

  • Theimaplib.IMAP4 class now handles flags containing the']' character in messages sent from the server to improvereal-world compatibility.(Contributed by Lita Cho inbpo-21815.)

  • Themmap.write() function now returns the numberof bytes written like other write methods.(Contributed by Jakub Stasiak inbpo-26335.)

  • Thepkgutil.iter_modules() andpkgutil.walk_packages()functions now returnModuleInfo named tuples.(Contributed by Ramchandra Apte inbpo-17211.)

  • re.sub() now raises an error for invalid numerical groupreferences in replacement templates even if the pattern is notfound in the string. The error message for invalid group referencesnow includes the group index and the position of the reference.(Contributed by SilentGhost, Serhiy Storchaka inbpo-25953.)

  • zipfile.ZipFile will now raiseNotImplementedError forunrecognized compression values. Previously a plainRuntimeErrorwas raised. Additionally, callingZipFile methodson a closed ZipFile or calling thewrite() methodon a ZipFile created with mode'r' will raise aValueError.Previously, aRuntimeError was raised in those scenarios.

  • when custom metaclasses are combined with zero-argumentsuper() ordirect references from methods to the implicit__class__ closurevariable, the implicit__classcell__ namespace entry must now be passedup totype.__new__ for initialisation. Failing to do so will result inaDeprecationWarning in Python 3.6 and aRuntimeError inPython 3.8.

  • With the introduction ofModuleNotFoundError, import system consumersmay start expecting import system replacements to raise that more specificexception when appropriate, rather than the less-specificImportError.To provide future compatibility with such consumers, implementers ofalternative import systems that completely replace__import__() willneed to update their implementations to raise the new subclass when a modulecan't be found at all. Implementers of compliant plugins to the defaultimport system shouldn't need to make any changes, as the default importsystem will raise the new subclass when appropriate.

C API 中的改動

CPython 位元組碼變更

There have been several major changes to thebytecode in Python 3.6.

  • The Python interpreter now uses a 16-bit wordcode instead of bytecode.(Contributed by Demur Rumed with input and reviews fromSerhiy Storchaka and Victor Stinner inbpo-26647 andbpo-28050.)

  • The newFORMAT_VALUE andBUILD_STRING opcodes as partof theformatted string literal implementation.(Contributed by Eric Smith inbpo-25483 andSerhiy Storchaka inbpo-27078.)

  • The newBUILD_CONST_KEY_MAP opcode to optimize the creationof dictionaries with constant keys.(Contributed by Serhiy Storchaka inbpo-27140.)

  • The function call opcodes have been heavily reworked for better performanceand simpler implementation.TheMAKE_FUNCTION,CALL_FUNCTION,CALL_FUNCTION_KW andBUILD_MAP_UNPACK_WITH_CALL opcodeshave been modified, the newCALL_FUNCTION_EX andBUILD_TUPLE_UNPACK_WITH_CALL have been added, andCALL_FUNCTION_VAR,CALL_FUNCTION_VAR_KW andMAKE_CLOSURE opcodeshave been removed.(Contributed by Demur Rumed inbpo-27095, and Serhiy Storchaka inbpo-27213,bpo-28257.)

  • The newSETUP_ANNOTATIONS andSTORE_ANNOTATION opcodeshave been added to support the newvariable annotation syntax.(Contributed by Ivan Levkivskyi inbpo-27985.)

Python 3.6.2 中顯著的變更

Newmakeregen-all build target

To simplify cross-compilation, and to ensure that CPython can reliably becompiled without requiring an existing version of Python to already beavailable, the autotools-based build system no longer attempts to implicitlyrecompile generated files based on file modification times.

Instead, a newmakeregen-all command has been added to force regenerationof these files when desired (e.g. after an initial version of Python hasalready been built based on the pregenerated versions).

More selective regeneration targets are also defined - seeMakefile.pre.in for details.

(由 Victor Stinner 於bpo-23404 中貢獻。)

在 3.6.2 版被加入.

Removal ofmaketouch build target

Themaketouch build target previously used to request implicit regenerationof generated files by updating their modification times has been removed.

It has been replaced by the newmakeregen-all target.

(由 Victor Stinner 於bpo-23404 中貢獻。)

在 3.6.2 版的變更.

Python 3.6.4 中顯著的變更

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.)

Python 3.6.5 中顯著的變更

Thelocale.localeconv() function now sets temporarily theLC_CTYPElocale to theLC_NUMERIC locale in some cases.(Contributed by Victor Stinner inbpo-31900.)

Python 3.6.7 中顯著的變更

xml.dom.minidom andxml.sax modules no longer processexternal entities by default. See alsogh-61441.

In 3.6.7 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.6.10 中顯著的變更

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.6.13 中顯著的變更

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.6.14 中顯著的變更

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)