Python 3.3 有什麼新功能¶
本文介紹了 Python 3.3 與 3.2 相比多了哪些新功能。Python 3.1 已於 2012 年 9 月 29 日發布。完整詳情請見changelog。
也參考
PEP 398 - Python 3.3 發佈時程
發布重點摘要¶
新增語法特性:
New
yieldfrom
expression forgenerator delegation.str
物件再次接受u'unicode'
語法。
新的函式庫模組:
faulthandler
(helps debugging low-level crashes)ipaddress
(high-level objects representing IP addresses and masks)lzma
(compress data using the XZ / LZMA algorithm)unittest.mock
(replace parts of your system under test with mock objects)venv
(Pythonvirtual environments, as in thepopularvirtualenv
package)
新的內建功能:
重新設計I/O 例外層次結構。
實作改進:
Rewrittenimport machinery based on
importlib
.More compactunicode strings.
More compactattribute dictionaries.
顯著改進的函式庫模組:
C Accelerator for thedecimal module.
Better unicode handling in theemail module(provisional).
安全性改進:
預設情況下,雜湊隨機化處於打開狀態。
Please read on for a comprehensive list of user-facing changes.
PEP 405:虛擬環境¶
Virtual environments help create separate Python setups while sharing asystem-wide base install, for ease of maintenance. Virtual environmentshave their own set of private site packages (i.e. locally installedlibraries), and are optionally segregated from the system-wide sitepackages. Their concept and implementation are inspired by the popularvirtualenv
third-party package, but benefit from tighter integrationwith the interpreter core.
This PEP adds thevenv
module for programmatic access, and thepyvenv
script for command-line access andadministration. The Python interpreter checks for apyvenv.cfg
,file whose existence signals the base of a virtual environment's directorytree.
也參考
- PEP 405 - Python 虛擬環境
由 Carl Meyer 撰寫 PEP;由 Carl Meyer 與 Vinay Sajip 實作
PEP 420: Implicit Namespace Packages¶
Native support for package directories that don't require__init__.py
marker files and can automatically span multiple path segments (inspired byvarious third party approaches to namespace packages, as described inPEP 420)
也參考
- PEP 420 - Implicit Namespace Packages
由 Eric V. Smith 撰寫 PEP;由 Eric V. Smith 和 Barry Warsaw 實施
PEP 3118: New memoryview implementation and buffer protocol documentation¶
The implementation ofPEP 3118 has been significantly improved.
The new memoryview implementation comprehensively fixes all ownership andlifetime issues of dynamically allocated fields in the Py_buffer structthat led to multiple crash reports. Additionally, several functions thatcrashed or returned incorrect results for non-contiguous or multi-dimensionalinput have been fixed.
The memoryview object now has a PEP-3118 compliant getbufferproc()that checks the consumer's request type. Many new features have beenadded, most of them work in full generality for non-contiguous arraysand arrays with suboffsets.
The documentation has been updated, clearly spelling out responsibilitiesfor both exporters and consumers. Buffer request flags are grouped intobasic and compound flags. The memory layout of non-contiguous andmulti-dimensional NumPy-style arrays is explained.
功能¶
All native single character format specifiers in struct module syntax(optionally prefixed with '@') are now supported.
With some restrictions, the cast() method allows changing of format andshape of C-contiguous arrays.
Multi-dimensional list representations are supported for any array type.
Multi-dimensional comparisons are supported for any array type.
One-dimensional memoryviews of hashable (read-only) types with formats B,b or c are now hashable. (Contributed by Antoine Pitrou inbpo-13411.)
Arbitrary slicing of any 1-D arrays type is supported. For example, itis now possible to reverse a memoryview inO(1) by using a negative step.
API 變更¶
The maximum number of dimensions is officially limited to 64.
The representation of empty shape, strides and suboffsets is nowan empty tuple instead of
None
.Accessing a memoryview element with format 'B' (unsigned bytes)now returns an integer (in accordance with the struct module syntax).For returning a bytes object the view must be cast to 'c' first.
memoryview comparisons now use the logical structure of the operandsand compare all array elements by value. All format strings in structmodule syntax are supported. Views with unrecognised format stringsare still permitted, but will always compare as unequal, regardlessof view contents.
For further changes seeBuild and C API Changes andPorting C code.
(由 Stefan Krah 在bpo-10181 中貢獻。)
也參考
PEP 3118 - 修訂緩衝協定
PEP 393: Flexible String Representation¶
The Unicode string type is changed to support multiple internalrepresentations, depending on the character with the largest Unicode ordinal(1, 2, or 4 bytes) in the represented string. This allows a space-efficientrepresentation in common cases, but gives access to full UCS-4 on allsystems. For compatibility with existing APIs, several representations mayexist in parallel; over time, this compatibility should be phased out.
On the Python side, there should be no downside to this change.
On the C API side,PEP 393 is fully backward compatible. The legacy APIshould remain available at least five years. Applications using the legacyAPI will not fully benefit of the memory reduction, or - worse - may usea bit more memory, because Python may have to maintain two versions of eachstring (in the legacy format and in the new efficient storage).
功能性¶
PEP 393 引入的更改如下:
Python now always supports the full range of Unicode code points, includingnon-BMP ones (i.e. from
U+0000
toU+10FFFF
). The distinction betweennarrow and wide builds no longer exists and Python now behaves like a widebuild, even under Windows.With the death of narrow builds, the problems specific to narrow builds havealso been fixed, for example:
len()
now always returns 1 for non-BMP characters,solen('\U0010FFFF')==1
;surrogate pairs are not recombined in string literals,so
'\uDBFF\uDFFF'!='\U0010FFFF'
;indexing or slicing non-BMP characters returns the expected value,so
'\U0010FFFF'[0]
now returns'\U0010FFFF'
and not'\uDBFF'
;all other functions in the standard library now correctly handlenon-BMP code points.
The value of
sys.maxunicode
is now always1114111
(0x10FFFF
in hexadecimal). ThePyUnicode_GetMax()
function still returnseither0xFFFF
or0x10FFFF
for backward compatibility, and it shouldnot be used with the new Unicode API (seebpo-13054)../configure
旗標--with-wide-unicode
已被刪除。
性能和資源使用情況¶
The storage of Unicode strings now depends on the highest code point in the string:
pure ASCII and Latin1 strings (
U+0000-U+00FF
) use 1 byte per code point;BMP strings (
U+0000-U+FFFF
) use 2 bytes per code point;non-BMP strings (
U+10000-U+10FFFF
) use 4 bytes per code point.
The net effect is that for most applications, memory usage of stringstorage should decrease significantly - especially compared to formerwide unicode builds - as, in many cases, strings will be pure ASCIIeven in international contexts (because many strings store non-humanlanguage data, such as XML fragments, HTTP headers, JSON-encoded data,etc.). We also hope that it will, for the same reasons, increase CPUcache efficiency on non-trivial applications. The memory usage ofPython 3.3 is two to three times smaller than Python 3.2, and a littlebit better than Python 2.7, on a Django benchmark (see the PEP fordetails).
也參考
- PEP 393 - Flexible String Representation
PEP 由 Martin von Löwis 撰寫;由 Torsten Becker 和 Martin von Löwis 實作。
PEP 397:適用於 Windows 的 Python 啟動器¶
The Python 3.3 Windows installer now includes apy
launcher applicationthat can be used to launch Python applications in a version independentfashion.
This launcher is invoked implicitly when double-clicking*.py
files.If only a single Python version is installed on the system, that versionwill be used to run the file. If multiple versions are installed, the mostrecent version is used by default, but this can be overridden by includinga Unix-style "shebang line" in the Python script.
The launcher can also be used explicitly from the command line as thepy
application. Runningpy
follows the same version selection rules asimplicitly launching scripts, but a more specific version can be selectedby passing appropriate arguments (such as-3
to request Python 3 whenPython 2 is also installed, or-2.6
to specifically request an earlierPython version when a more recent version is installed).
In addition to the launcher, the Windows installer now includes anoption to add the newly installed Python to the system PATH. (Contributedby Brian Curtin inbpo-3561.)
也參考
- PEP 397 - 適用於 Windows 的 Python 啟動器
由 Mark Hammond 和 Martin v. Löwis 撰寫 PEP;由 Vinay Sajip 實作。
啟動器文件:Python Launcher for Windows
Installer PATH modification:Finding the Python executable
PEP 3151: Reworking the OS and IO exception hierarchy¶
The hierarchy of exceptions raised by operating system errors is now bothsimplified and finer-grained.
You don't have to worry anymore about choosing the appropriate exceptiontype betweenOSError
,IOError
,EnvironmentError
,WindowsError
,mmap.error
,socket.error
orselect.error
. All these exception types are now only one:OSError
. The other names are kept as aliases for compatibilityreasons.
Also, it is now easier to catch a specific error condition. Instead ofinspecting theerrno
attribute (orargs[0]
) for a particularconstant from theerrno
module, you can catch the adequateOSError
subclass. The available subclasses are the following:
And theConnectionError
itself has finer-grained subclasses:
Thanks to the new exceptions, common usages of theerrno
can now beavoided. For example, the following code written for Python 3.2:
fromerrnoimportENOENT,EACCES,EPERMtry:withopen("document.txt")asf:content=f.read()exceptIOErroraserr:iferr.errno==ENOENT:print("document.txt file is missing")eliferr.errnoin(EACCES,EPERM):print("You are not allowed to read document.txt")else:raise
can now be written without theerrno
import and without manualinspection of exception attributes:
try:withopen("document.txt")asf:content=f.read()exceptFileNotFoundError:print("document.txt file is missing")exceptPermissionError:print("You are not allowed to read document.txt")
也參考
- PEP 3151 - Reworking the OS and IO Exception Hierarchy
由 Antoine Pitrou 撰寫 PEP 與實作
PEP 380: Syntax for Delegating to a Subgenerator¶
PEP 380 adds theyieldfrom
expression, allowing agenerator todelegatepart of its operations to another generator. This allows a section of codecontainingyield
to be factored out and placed in another generator.Additionally, the subgenerator is allowed to return with a value, and thevalue is made available to the delegating generator.
While designed primarily for use in delegating to a subgenerator, theyieldfrom
expression actually allows delegation to arbitrary subiterators.
For simple iterators,yieldfromiterable
is essentially just a shortenedform offoriteminiterable:yielditem
:
>>>defg(x):...yield fromrange(x,0,-1)...yield fromrange(x)...>>>list(g(5))[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
However, unlike an ordinary loop,yieldfrom
allows subgenerators toreceive sent and thrown values directly from the calling scope, andreturn a final value to the outer generator:
>>>defaccumulate():...tally=0...while1:...next=yield...ifnextisNone:...returntally...tally+=next...>>>defgather_tallies(tallies):...while1:...tally=yield fromaccumulate()...tallies.append(tally)...>>>tallies=[]>>>acc=gather_tallies(tallies)>>>next(acc)# Ensure the accumulator is ready to accept values>>>foriinrange(4):...acc.send(i)...>>>acc.send(None)# Finish the first tally>>>foriinrange(5):...acc.send(i)...>>>acc.send(None)# Finish the second tally>>>tallies[6, 10]
The main principle driving this change is to allow even generators that aredesigned to be used with thesend
andthrow
methods to be split intomultiple subgenerators as easily as a single large function can be split intomultiple subfunctions.
也參考
- PEP 380 - Syntax for Delegating to a Subgenerator
PEP written by Greg Ewing; implementation by Greg Ewing, integrated into3.3 by Renaud Blanch, Ryan Kelly and Nick Coghlan; documentation byZbigniew Jędrzejewski-Szmek and Nick Coghlan
PEP 409: Suppressing exception context¶
PEP 409 introduces new syntax that allows the display of the chainedexception context to be disabled. This allows cleaner error messages inapplications that convert between exception types:
>>>classD:...def__init__(self,extra):...self._extra_attributes=extra...def__getattr__(self,attr):...try:...returnself._extra_attributes[attr]...exceptKeyError:...raiseAttributeError(attr)fromNone...>>>D({}).xTraceback (most recent call last): File"<stdin>", line1, in<module> File"<stdin>", line8, in__getattr__AttributeError:x
Without thefromNone
suffix to suppress the cause, the originalexception would be displayed by default:
>>>classC:...def__init__(self,extra):...self._extra_attributes=extra...def__getattr__(self,attr):...try:...returnself._extra_attributes[attr]...exceptKeyError:...raiseAttributeError(attr)...>>>C({}).xTraceback (most recent call last): File"<stdin>", line6, in__getattr__KeyError:'x'During handling of the above exception, another exception occurred:Traceback (most recent call last): File"<stdin>", line1, in<module> File"<stdin>", line8, in__getattr__AttributeError:x
No debugging capability is lost, as the original exception context remainsavailable if needed (for example, if an intervening library has incorrectlysuppressed valuable underlying details):
>>>try:...D({}).x...exceptAttributeErrorasexc:...print(repr(exc.__context__))...KeyError('x',)
也參考
- PEP 409 - Suppressing exception context
PEP written by Ethan Furman; implemented by Ethan Furman and NickCoghlan.
PEP 414: Explicit Unicode literals¶
To ease the transition from Python 2 for Unicode aware Python applicationsthat make heavy use of Unicode literals, Python 3.3 once again supports the"u
" prefix for string literals. This prefix has no semantic significancein Python 3, it is provided solely to reduce the number of purely mechanicalchanges in migrating to Python 3, making it easier for developers to focus onthe more significant semantic changes (such as the stricter defaultseparation of binary and text data).
也參考
- PEP 414 - Explicit Unicode literals
由 Armin Ronacher 撰寫 PEP。
PEP 3155: Qualified name for classes and functions¶
Functions and class objects have a new__qualname__
attribute representingthe "path" from the module top-level to their definition. For global functionsand classes, this is the same as__name__
.For other functions and classes,it provides better information about where they were actually defined, andhow they might be accessible from the global scope.
Example with (non-bound) methods:
>>>classC:...defmeth(self):...pass...>>>C.meth.__name__'meth'>>>C.meth.__qualname__'C.meth'
巢狀類別範例:
>>>classC:...classD:...defmeth(self):...pass...>>>C.D.__name__'D'>>>C.D.__qualname__'C.D'>>>C.D.meth.__name__'meth'>>>C.D.meth.__qualname__'C.D.meth'
巢狀函式範例:
>>>defouter():...definner():...pass...returninner...>>>outer().__name__'inner'>>>outer().__qualname__'outer.<locals>.inner'
The string representation of those objects is also changed to include thenew, more precise information:
>>>str(C.D)"<class '__main__.C.D'>">>>str(C.D.meth)'<function C.D.meth at 0x7f46b9fe31e0>'
也參考
- PEP 3155 - Qualified name for classes and functions
由 Antoine Pitrou 撰寫 PEP 與實作。
PEP 412: Key-Sharing Dictionary¶
Dictionaries used for the storage of objects' attributes are now able toshare part of their internal storage between each other (namely, the partwhich stores the keys and their respective hashes). This reduces the memoryconsumption of programs creating many instances of non-builtin types.
也參考
- PEP 412 - 密鑰共享字典
由 Mark Shannon 撰寫 PEP 與實作。
PEP 362:函式簽名物件¶
A new functioninspect.signature()
makes introspection of pythoncallables easy and straightforward. A broad range of callables is supported:python functions, decorated or not, classes, andfunctools.partial()
objects. New classesinspect.Signature
,inspect.Parameter
andinspect.BoundArguments
hold information about the call signatures,such as, annotations, default values, parameters kinds, and bound arguments,which considerably simplifies writing decorators and any code that validatesor amends calling signatures or arguments.
也參考
- PEP 362: - 函式簽名物件
PEP 由 Brett Cannon、Yury Selivanov、Larry Hastings、Jiwon Seo 撰寫;由 Yury Selivanov 實作。
PEP 421:新增 sys.implementation¶
A new attribute on thesys
module exposes details specific to theimplementation of the currently running interpreter. The initial set ofattributes onsys.implementation
arename
,version
,hexversion
, andcache_tag
.
The intention ofsys.implementation
is to consolidate into one namespacethe implementation-specific data used by the standard library. This allowsdifferent Python implementations to share a single standard library code basemuch more easily. In its initial state,sys.implementation
holds only asmall portion of the implementation-specific data. Over time that ratio willshift in order to make the standard library more portable.
One example of improved standard library portability iscache_tag
. As ofPython 3.3,sys.implementation.cache_tag
is used byimportlib
tosupportPEP 3147 compliance. Any Python implementation that usesimportlib
for its built-in import system may usecache_tag
to controlthe caching behavior for modules.
SimpleNamespace¶
The implementation ofsys.implementation
also introduces a new type toPython:types.SimpleNamespace
. In contrast to a mapping-basednamespace, likedict
,SimpleNamespace
is attribute-based, likeobject
. However, unlikeobject
,SimpleNamespace
instancesare writable. This means that you can add, remove, and modify the namespacethrough normal attribute access.
也參考
- PEP 421 - 新增 sys.implementation
由 Eric Snow 撰寫 PEP 與實作。
使用 importlib 作為 import 的實作¶
bpo-2377 - Replace __import__ w/ importlib.__import__bpo-13959 - Re-implement parts ofimp
in pure Pythonbpo-14605 - Make import machinery explicitbpo-14646 - Require loaders set __loader__ and __package__
The__import__()
function is now powered byimportlib.__import__()
.This work leads to the completion of "phase 2" ofPEP 302. There aremultiple benefits to this change. First, it has allowed for more of themachinery powering import to be exposed instead of being implicit and hiddenwithin the C code. It also provides a single implementation for all Python VMssupporting Python 3.3 to use, helping to end any VM-specific deviations inimport semantics. And finally it eases the maintenance of import, allowing forfuture growth to occur.
For the common user, there should be no visible change in semantics. Forthose whose code currently manipulates import or calls importprogrammatically, the code changes that might possibly be required are coveredin thePorting Python code section of this document.
新 API¶
One of the large benefits of this work is the exposure of what goes intomaking the import statement work. That means the various importers that wereonce implicit are now fully exposed as part of theimportlib
package.
The abstract base classes defined inimportlib.abc
have been expandedto properly delineate betweenmeta path findersandpath entry finders by introducingimportlib.abc.MetaPathFinder
andimportlib.abc.PathEntryFinder
, respectively. The old ABC ofimportlib.abc.Finder
is now only provided for backwards-compatibilityand does not enforce any method requirements.
In terms of finders,importlib.machinery.FileFinder
exposes themechanism used to search for source and bytecode files of a module. Previouslythis class was an implicit member ofsys.path_hooks
.
For loaders, the new abstract base classimportlib.abc.FileLoader
helpswrite a loader that uses the file system as the storage mechanism for a module'scode. The loader for source files(importlib.machinery.SourceFileLoader
), sourceless bytecode files(importlib.machinery.SourcelessFileLoader
), and extension modules(importlib.machinery.ExtensionFileLoader
) are now available fordirect use.
ImportError
now hasname
andpath
attributes which are set whenthere is relevant data to provide. The message for failed imports will alsoprovide the full name of the module now instead of just the tail end of themodule's name.
Theimportlib.invalidate_caches()
function will now call the method withthe same name on all finders cached insys.path_importer_cache
to helpclean up any stored state as necessary.
明顯的變更¶
For potential required changes to code, see thePorting Python codesection.
Beyond the expanse of whatimportlib
now exposes, there are othervisible changes to import. The biggest is thatsys.meta_path
andsys.path_hooks
now store all of the meta path finders and path entryhooks used by import. Previously the finders were implicit and hidden withinthe C code of import instead of being directly exposed. This means that one cannow easily remove or change the order of the various finders to fit one's needs.
Another change is that all modules have a__loader__
attribute, storing theloader used to create the module.PEP 302 has been updated to make thisattribute mandatory for loaders to implement, so in the future once 3rd-partyloaders have been updated people will be able to rely on the existence of theattribute. Until such time, though, import is setting the module post-load.
Loaders are also now expected to set the__package__
attribute fromPEP 366. Once again, import itself is already setting this on all loadersfromimportlib
and import itself is setting the attribute post-load.
None
is now inserted intosys.path_importer_cache
when no findercan be found onsys.path_hooks
. Sinceimp.NullImporter
is notdirectly exposed onsys.path_hooks
it could no longer be relied upon toalways be available to use as a value representing no finder found.
All other changes relate to semantic changes which should be taken intoconsideration when updating code for Python 3.3, and thus should be read aboutin thePorting Python code section of this document.
(由 Brett Cannon 實作)
其他語言更動¶
對核心 Python 語言所做的一些較小的更改包括:
Added support for Unicode name aliases and named sequences.Both
unicodedata.lookup()
and'\N{...}'
now resolve name aliases,andunicodedata.lookup()
resolves named sequences too.(由 Ezio Melotti 在bpo-12753 中貢獻。)
Unicode 資料庫更新至 UCD 版本 6.1.0
Equality comparisons on
range()
objects now return a result reflectingthe equality of the underlying sequences generated by those range objects.(bpo-13201)The
count()
,find()
,rfind()
,index()
andrindex()
methods ofbytes
andbytearray
objects now accept aninteger between 0 and 255 as their first argument.(由 Petri Lehtinen 在bpo-12170 中貢獻。)
The
rjust()
,ljust()
, andcenter()
methods ofbytes
andbytearray
now accept abytearray
for thefill
argument. (Contributed by Petri Lehtinen inbpo-12380.)New methods have been added to
list
andbytearray
:copy()
andclear()
(bpo-10516). Consequently,MutableSequence
now also defines aclear()
method (bpo-11388).Raw bytes literals can now be written
rb"..."
as well asbr"..."
.(由 Antoine Pitrou 在bpo-13748 中貢獻。)
dict.setdefault()
now does only one lookup for the given key, makingit atomic when used with built-in types.(由 Filip Gruszczyński 在bpo-13521 中貢獻。)
The error messages produced when a function call does not match the functionsignature have been significantly improved.
(由 Benjamin Peterson 貢獻。)
A Finer-Grained Import Lock¶
Previous versions of CPython have always relied on a global import lock.This led to unexpected annoyances, such as deadlocks when importing a modulewould trigger code execution in a different thread as a side-effect.Clumsy workarounds were sometimes employed, such as thePyImport_ImportModuleNoBlock()
C API function.
In Python 3.3, importing a module takes a per-module lock. This correctlyserializes importation of a given module from multiple threads (preventingthe exposure of incompletely initialized modules), while eliminating theaforementioned annoyances.
(由 Antoine Pitrou 在bpo-9260 中貢獻。)
內建函式和型別¶
open()
gets a newopener parameter: the underlying file descriptorfor the file object is then obtained by callingopener with (file,flags). It can be used to use custom flags likeos.O_CLOEXEC
forexample. The'x'
mode was added: open for exclusive creation, failing ifthe file already exists.print()
: added theflush keyword argument. If theflush keywordargument is true, the stream is forcibly flushed.hash()
: hash randomization is enabled by default, seeobject.__hash__()
andPYTHONHASHSEED
.The
str
type gets a newcasefold()
method: return acasefolded copy of the string, casefolded strings may be used for caselessmatching. For example,'ß'.casefold()
returns'ss'
.The sequence documentation has been substantially rewritten to betterexplain the binary/text sequence distinction and to provide specificdocumentation sections for the individual builtin sequence types(bpo-4966).
新模組¶
faulthandler¶
This new debug modulefaulthandler
contains functions to dump Python tracebacks explicitly,on a fault (a crash like a segmentation fault), after a timeout, or on a usersignal. Callfaulthandler.enable()
to install fault handlers for theSIGSEGV
,SIGFPE
,SIGABRT
,SIGBUS
, andSIGILL
signals. You can also enable them at startup by setting thePYTHONFAULTHANDLER
environment variable or by using-X
faulthandler
command line option.
Example of a segmentation fault on Linux:
$python-q-Xfaulthandler>>> import ctypes>>> ctypes.string_at(0)Fatal Python error: Segmentation faultCurrent thread 0x00007fb899f39700: File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at File "<stdin>", line 1 in <module>Segmentation fault
ipaddress¶
The newipaddress
module provides tools for creating and manipulatingobjects representing IPv4 and IPv6 addresses, networks and interfaces (i.e.an IP address associated with a specific IP subnet).
(由 Google 和 Peter Moody 在PEP 3144 中貢獻。)
lzma¶
The newly addedlzma
module provides data compression and decompressionusing the LZMA algorithm, including support for the.xz
and.lzma
file formats.
(由 Nadeem Vawda 和 Per Øyvind Karlsen 在bpo-6715 中貢獻。)
改進的模組¶
abc¶
Improved support for abstract base classes containing descriptors composed withabstract methods. The recommended approach to declaring abstract descriptors isnow to provide__isabstractmethod__
as a dynamically updatedproperty. The built-in descriptors have been updated accordingly.
abc.abstractclassmethod
已被棄用,請改用classmethod
和abc.abstractmethod()
。abc.abstractstaticmethod
已被棄用,請改用staticmethod
和abc.abstractmethod()
。
(由 Darren Dale 在bpo-11610 中貢獻。)
abc.ABCMeta.register()
now returns the registered subclass, which meansit can now be used as a class decorator (bpo-10868).
array¶
Thearray
module supports thelonglong type usingq
andQ
type codes.
(由 Oren Tirosh 和 Hirokazu Yamamoto 在bpo-1172711 中貢獻。)
base64¶
ASCII-only Unicode strings are now accepted by the decoding functions of thebase64
modern interface. For example,base64.b64decode('YWJj')
returnsb'abc'
. (Contributed by Catalin Iacob inbpo-13641.)
binascii¶
In addition to the binary objects they normally accept, thea2b_
functionsnow all also accept ASCII-only strings as input. (Contributed by AntoinePitrou inbpo-13637.)
bz2¶
Thebz2
module has been rewritten from scratch. In the process, severalnew features have been added:
New
bz2.open()
function: open a bzip2-compressed file in binary ortext mode.bz2.BZ2File
can now read from and write to arbitrary file-likeobjects, by means of its constructor'sfileobj argument.(由 Nadeem Vawda 在bpo-5863 中貢獻。)
bz2.BZ2File
andbz2.decompress()
can now decompressmulti-stream inputs (such as those produced by thepbzip2 tool).bz2.BZ2File
can now also be used to create this type of file, usingthe'a'
(append) mode.(由 Nir Aides 在bpo-1625 中貢獻。)
bz2.BZ2File
now implements all of theio.BufferedIOBase
API,except for thedetach()
andtruncate()
methods.
codecs¶
Thembcs
codec has been rewritten to handle correctlyreplace
andignore
error handlers on all Windows versions. Thembcs
codec now supports all error handlers, instead of onlyreplace
to encode andignore
to decode.
A new Windows-only codec has been added:cp65001
(bpo-13216). It is theWindows code page 65001 (Windows UTF-8,CP_UTF8
). For example, it is usedbysys.stdout
if the console output code page is set to cp65001 (e.g., usingchcp65001
command).
Multibyte CJK decoders now resynchronize faster. They only ignore the firstbyte of an invalid byte sequence. For example,b'\xff\n'.decode('gb2312','replace')
now returns a\n
after the replacement character.
Incremental CJK codec encoders are no longer reset at each call to theirencode() methods. For example:
>>>importcodecs>>>encoder=codecs.getincrementalencoder('hz')('strict')>>>b''.join(encoder.encode(x)forxin'\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')b'~{NpJ)l6HK!#~} Bye.'
This example givesb'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~}Bye.'
with older Pythonversions.
unicode_internal
編解碼器已被棄用。
collections¶
Addition of a newChainMap
class to allow treating anumber of mappings as a single unit. (Written by Raymond Hettinger forbpo-11089, made public inbpo-11297.)
The abstract base classes have been moved in a newcollections.abc
module, to better differentiate between the abstract and the concretecollections classes. Aliases for ABCs are still present in thecollections
module to preserve existing imports. (bpo-11085)
TheCounter
class now supports the unary+
and-
operators, as well as the in-place operators+=
,-=
,|=
, and&=
. (Contributed by Raymond Hettinger inbpo-13121.)
contextlib¶
ExitStack
now provides a solid foundation forprogrammatic manipulation of context managers and similar cleanupfunctionality. Unlike the previouscontextlib.nested
API (which wasdeprecated and removed), the new API is designed to work correctlyregardless of whether context managers acquire their resources intheir__init__
method (for example, file objects) or in their__enter__
method (for example, synchronisation objects from thethreading
module).
crypt¶
Addition of salt and modular crypt format (hashing method) and themksalt()
function to thecrypt
module.
curses¶
If the
curses
module is linked to the ncursesw library, use Unicodefunctions when Unicode strings or characters are passed (e.g.waddwstr()
), and bytes functions otherwise (e.g.waddstr()
).Use the locale encoding instead of
utf-8
to encode Unicode strings.curses.window
有一個新的curses.window.encoding
屬性。curses.window
類別有一個新的get_wch()
方法來獲取寬字元The
curses
module has a newunget_wch()
function topush a wide character so the nextget_wch()
will returnit
(由 Iñigo Serna 在bpo-6755 中貢獻。)
datetime¶
Equality comparisons between naive and aware
datetime
instances now returnFalse
instead of raisingTypeError
(bpo-15006).New
datetime.datetime.timestamp()
method: Return POSIX timestampcorresponding to thedatetime
instance.The
datetime.datetime.strftime()
method supports formatting yearsolder than 1000.The
datetime.datetime.astimezone()
method can now becalled without arguments to convert datetime instance to the systemtimezone.
decimal¶
- bpo-7652 - integrate fast native decimal arithmetic.
由 Stefan Krah 編寫的 C 模組和 libmpdec。
The new C version of the decimal module integrates the high speed libmpdeclibrary for arbitrary precision correctly rounded decimal floating-pointarithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.
Performance gains range from 10x for database applications to 100x fornumerically intensive applications. These numbers are expected gainsfor standard precisions used in decimal floating-point arithmetic. Sincethe precision is user configurable, the exact figures may vary. For example,in integer bignum arithmetic the differences can be significantly higher.
The following table is meant as an illustration. Benchmarks are availableathttps://www.bytereef.org/mpdecimal/quickstart.html.
decimal.py
_decimal
speedup
pi
42.02s
0.345s
120x
telco
172.19s
5.68s
30x
psycopg
3.57s
0.29s
12x
功能¶
The
FloatOperation
signal optionally enables strictersemantics for mixing floats and Decimals.If Python is compiled without threads, the C version automaticallydisables the expensive thread local context machinery. In this case,the variable
HAVE_THREADS
is set toFalse
.
API 變更¶
The C module has the following context limits, depending on the machinearchitecture:
32 位元
64 位元
MAX_PREC
425000000
999999999999999999
MAX_EMAX
425000000
999999999999999999
MIN_EMIN
-425000000
-999999999999999999
In the context templates (
DefaultContext
,BasicContext
andExtendedContext
)the magnitude ofEmax
andEmin
has changed to999999
.The
Decimal
constructor in decimal.py does not observethe context limits and converts values with arbitrary exponents or precisionexactly. Since the C version has internal limits, the following scheme isused: If possible, values are converted exactly, otherwiseInvalidOperation
is raised and the result is NaN. In thelatter case it is always possible to usecreate_decimal()
in order to obtain a rounded or inexact value.The power function in decimal.py is always correctly rounded. In theC version, it is defined in terms of the correctly rounded
exp()
andln()
functions,but the final result is only "almost always correctly rounded".In the C version, the context dictionary containing the signals is a
MutableMapping
. For speed reasons,flags
andtraps
alwaysrefer to the sameMutableMapping
that the contextwas initialized with. If a new signal dictionary is assigned,flags
andtraps
are updated with the new values, but they do not reference the RHSdictionary.Pickling a
Context
produces a different output in orderto have a common interchange format for the Python and C versions.The order of arguments in the
Context
constructor has beenchanged to match the order displayed byrepr()
.quantize()
方法中的watchexp
參數已棄用。
email¶
Policy Framework¶
The email package now has apolicy
framework. APolicy
is an object with several methods and propertiesthat control how the email package behaves. The primary policy for Python 3.3is theCompat32
policy, which provides backwardcompatibility with the email package in Python 3.2. Apolicy
can bespecified when an email message is parsed by aparser
, or when aMessage
object is created, or when an email isserialized using agenerator
. Unless overridden, a policy passedto aparser
is inherited by all theMessage
object and sub-objectscreated by theparser
. By default agenerator
will use the policy oftheMessage
object it is serializing. The default policy iscompat32
.
The minimum set of controls implemented by allpolicy
objects are:
max_line_length | The maximum length, excluding the linesep character(s),individual lines may have when a |
linesep | The character used to separate individual lines when a |
cte_type |
|
raise_on_defect | Causes a |
A new policy instance, with new settings, is created using theclone()
method of policy objects.clone
takesany of the above controls as keyword arguments. Any control not specified inthe call retains its default value. Thus you can create a policy that uses\r\n
linesep characters like this:
mypolicy=compat32.clone(linesep='\r\n')
Policies can be used to make the generation of messages in the format needed byyour application simpler. Instead of having to remember to specifylinesep='\r\n'
in all the places you call agenerator
, you can specifyit once, when you set the policy used by theparser
or theMessage
,whichever your program uses to createMessage
objects. On the other hand,if you need to generate messages in multiple forms, you can still specify theparameters in the appropriategenerator
call. Or you can have custompolicy instances for your different cases, and pass those in when you createthegenerator
.
Provisional Policy with New Header API¶
While the policy framework is worthwhile all by itself, the main motivation forintroducing it is to allow the creation of new policies that implement newfeatures for the email package in a way that maintains backward compatibilityfor those who do not use the new policies. Because the new policies introduce anew API, we are releasing them in Python 3.3 as aprovisional policy. Backwards incompatible changes (up to and includingremoval of the code) may occur if deemed necessary by the core developers.
The new policies are instances ofEmailPolicy
,and add the following additional controls:
refold_source | Controls whether or not headers parsed by a |
header_factory | A callable that take a |
Theheader_factory
is the key to the new features provided by the newpolicies. When one of the new policies is used, any header retrieved fromaMessage
object is an object produced by theheader_factory
, and anytime you set a header on aMessage
it becomes an object produced byheader_factory
. All such header objects have aname
attribute equalto the header name. Address and Date headers have additional attributesthat give you access to the parsed data of the header. This means you can nowdo things like this:
>>>m=Message(policy=SMTP)>>>m['To']='Éric <foo@example.com>'>>>m['to']'Éric <foo@example.com>'>>>m['to'].addresses(Address(display_name='Éric', username='foo', domain='example.com'),)>>>m['to'].addresses[0].username'foo'>>>m['to'].addresses[0].display_name'Éric'>>>m['Date']=email.utils.localtime()>>>m['Date'].datetimedatetime.datetime(2012, 5, 25, 21, 39, 24, 465484, tzinfo=datetime.timezone(datetime.timedelta(-1, 72000), 'EDT'))>>>m['Date']'Fri, 25 May 2012 21:44:27 -0400'>>>print(m)To: =?utf-8?q?=C3=89ric?= <foo@example.com>Date: Fri, 25 May 2012 21:44:27 -0400
You will note that the unicode display name is automatically encoded asutf-8
when the message is serialized, but that when the header is accesseddirectly, you get the unicode version. This eliminates any need to deal withtheemail.header
decode_header()
ormake_header()
functions.
You can also create addresses from parts:
>>>m['cc']=[Group('pals',[Address('Bob','bob','example.com'),...Address('Sally','sally','example.com')]),...Address('Bonzo',addr_spec='bonz@laugh.com')]>>>print(m)To: =?utf-8?q?=C3=89ric?= <foo@example.com>Date: Fri, 25 May 2012 21:44:27 -0400cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>
解碼為 unicode 是自動完成的:
>>>m2=message_from_string(str(m))>>>m2['to']'Éric <foo@example.com>'
When you parse a message, you can use theaddresses
andgroups
attributes of the header objects to access the groups and individualaddresses:
>>>m2['cc'].addresses(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com'), Address(display_name='Bonzo', username='bonz', domain='laugh.com'))>>>m2['cc'].groups(Group(display_name='pals', addresses=(Address(display_name='Bob', username='bob', domain='example.com'), Address(display_name='Sally', username='sally', domain='example.com')), Group(display_name=None, addresses=(Address(display_name='Bonzo', username='bonz', domain='laugh.com'),))
In summary, if you use one of the new policies, header manipulation works theway it ought to: your application works with unicode strings, and the emailpackage transparently encodes and decodes the unicode to and from the RFCstandard Content Transfer Encodings.
其他 API 變更¶
NewBytesHeaderParser
, added to theparser
module to complementHeaderParser
and complete the BytesAPI.
新工具函式:
format_datetime()
: given adatetime
,produce a string formatted for use in an email header.parsedate_to_datetime()
: given a date string froman email header, convert it into an awaredatetime
,or a naivedatetime
if the offset is-0000
.localtime()
: With no argument, returns thecurrent local time as an awaredatetime
using the localtimezone
. Given an awaredatetime
,converts it into an awaredatetime
using thelocaltimezone
.
ftplib¶
ftplib.FTP
now accepts asource_address
keyword argument tospecify the(host,port)
to use as the source address in the bind callwhen creating the outgoing socket. (Contributed by Giampaolo Rodolàinbpo-8594.)The
FTP_TLS
class now provides a newccc()
function to revert control channel back toplaintext. This can be useful to take advantage of firewalls that know howto handle NAT with non-secure FTP without opening fixed ports. (Contributedby Giampaolo Rodolà inbpo-12139.)Added
ftplib.FTP.mlsd()
method which provides a parsable directorylisting format and deprecatesftplib.FTP.nlst()
andftplib.FTP.dir()
. (Contributed by Giampaolo Rodolà inbpo-11072.)
functools¶
Thefunctools.lru_cache()
decorator now accepts atyped
keywordargument (that defaults toFalse
to ensure that it caches values ofdifferent types that compare equal in separate cache slots. (Contributedby Raymond Hettinger inbpo-13227.)
gc¶
It is now possible to register callbacks invoked by the garbage collectorbefore and after collection using the newcallbacks
list.
hmac¶
A newcompare_digest()
function has been added to prevent sidechannel attacks on digests through timing analysis. (Contributed by NickCoghlan and Christian Heimes inbpo-15061.)
http¶
http.server.BaseHTTPRequestHandler
now buffers the headers and writesthem all at once whenend_headers()
iscalled. A new methodflush_headers()
can be used to directly manage when the accumulated headers are sent.(Contributed by Andrew Schaaf inbpo-3709.)
http.server
now produces validHTML4.01strict
output.(Contributed by Ezio Melotti inbpo-13295.)
http.client.HTTPResponse
now has areadinto()
method, which means it can be usedas anio.RawIOBase
class. (Contributed by John Kuhn inbpo-13464.)
html¶
html.parser.HTMLParser
is now able to parse broken markup withoutraising errors, therefore thestrict argument of the constructor and theHTMLParseError
exception are now deprecated.The ability to parse broken markup is the result of a number of bug fixes thatare also available on the latest bug fix releases of Python 2.7/3.2.(Contributed by Ezio Melotti inbpo-15114, andbpo-14538,bpo-13993,bpo-13960,bpo-13358,bpo-1745761,bpo-755670,bpo-13357,bpo-12629,bpo-1200313,bpo-670664,bpo-13273,bpo-12888,bpo-7311.)
A newhtml5
dictionary that maps HTML5 named characterreferences to the equivalent Unicode character(s) (e.g.html5['gt;']=='>'
) has been added to thehtml.entities
module. The dictionary isnow also used byHTMLParser
. (Contributed by EzioMelotti inbpo-11113 andbpo-15156.)
imaplib¶
TheIMAP4_SSL
constructor now accepts an SSLContextparameter to control parameters of the secure channel.
(由 Sijin Joseph 在bpo-8808 中貢獻。)
inspect¶
A newgetclosurevars()
function has been added. This functionreports the current binding of all names referenced from the function body andwhere those names were resolved, making it easier to verify correct internalstate when testing code that relies on stateful closures.
(由 Meador Inge 與 Nick Coghlan 在bpo-13062 中貢獻。)
A newgetgeneratorlocals()
function has been added. Thisfunction reports the current binding of local variables in the generator'sstack frame, making it easier to verify correct internal state when testinggenerators.
(由 Meador Inge 於bpo-15153 中貢獻。)
io¶
Theopen()
function has a new'x'
mode that can be used toexclusively create a new file, and raise aFileExistsError
if the filealready exists. It is based on the C11 'x' mode to fopen().
(由 David Townshend 於bpo-12760 中貢獻。)
The constructor of theTextIOWrapper
class has a newwrite_through optional argument. Ifwrite_through isTrue
, calls towrite()
are guaranteed not to be buffered: any datawritten on theTextIOWrapper
object is immediately handled to itsunderlying binary buffer.
itertools¶
accumulate()
now takes an optionalfunc
argument forproviding a user-supplied binary function.
logging¶
ThebasicConfig()
function now supports an optionalhandlers
argument taking an iterable of handlers to be added to the root logger.
A class level attributeappend_nul
hasbeen added toSysLogHandler
to allow control of theappending of theNUL
(\000
) byte to syslog records, since for somedaemons it is required while for others it is passed through to the log.
math¶
Themath
module has a new function,log2()
, which returnsthe base-2 logarithm ofx.
(由 Mark Dickinson 於bpo-11888 中撰寫)
mmap¶
Theread()
method is now more compatible with other file-likeobjects: if the argument is omitted or specified asNone
, it returns thebytes from the current file position to the end of the mapping. (Contributedby Petri Lehtinen inbpo-12021.)
multiprocessing¶
The newmultiprocessing.connection.wait()
function allows pollingmultiple objects (such as connections, sockets and pipes) with a timeout.(Contributed by Richard Oudkerk inbpo-12328.)
multiprocessing.Connection
objects can now be transferred overmultiprocessing connections.(Contributed by Richard Oudkerk inbpo-4892.)
multiprocessing.Process
now accepts adaemon
keyword argumentto override the default behavior of inheriting thedaemon
flag fromthe parent process (bpo-6064).
New attributemultiprocessing.Process.sentinel
allows aprogram to wait on multipleProcess
objects at onetime using the appropriate OS primitives (for example,select
onposix systems).
New methodsmultiprocessing.pool.Pool.starmap()
andstarmap_async()
provideitertools.starmap()
equivalents to the existingmultiprocessing.pool.Pool.map()
andmap_async()
functions. (Contributed by HynekSchlawack inbpo-12708.)
nntplib¶
Thenntplib.NNTP
class now supports the context management protocol tounconditionally consumesocket.error
exceptions and to close the NNTPconnection when done:
>>>fromnntplibimportNNTP>>>withNNTP('news.gmane.org')asn:...n.group('gmane.comp.python.committers')...('211 1755 1 1755 gmane.comp.python.committers', 1755, 1, 1755, 'gmane.comp.python.committers')>>>
(由 Giampaolo Rodolà 於bpo-9795 中貢獻。)
os¶
The
os
module has a newpipe2()
function that makes itpossible to create a pipe withO_CLOEXEC
orO_NONBLOCK
flags set atomically. This is especially useful toavoid race conditions in multi-threaded programs.The
os
module has a newsendfile()
function which providesan efficient "zero-copy" way for copying data from one file (or socket)descriptor to another. The phrase "zero-copy" refers to the fact that all ofthe copying of data between the two descriptors is done entirely by thekernel, with no copying of data into userspace buffers.sendfile()
can be used to efficiently copy data from a file on disk to a network socket,e.g. for downloading a file.(由 Ross Lagerwall 和 Giampaolo Rodolà 於bpo-10882 提交補丁。)
To avoid race conditions like symlink attacks and issues with temporaryfiles and directories, it is more reliable (and also faster) to manipulatefile descriptors instead of file names. Python 3.3 enhances existing functionsand introduces new functions to work on file descriptors (bpo-4761,bpo-10755 andbpo-14626).
The
os
module has a newfwalk()
function similar towalk()
except that it also yields file descriptors referring to thedirectories visited. This is especially useful to avoid symlink races.The following functions get new optionaldir_fd (paths relative todirectory descriptors) and/orfollow_symlinks (notfollowing symlinks):
access()
,chflags()
,chmod()
,chown()
,link()
,lstat()
,mkdir()
,mkfifo()
,mknod()
,open()
,readlink()
,remove()
,rename()
,replace()
,rmdir()
,stat()
,symlink()
,unlink()
,utime()
. Platformsupport for using these parameters can be checked via the setsos.supports_dir_fd
andos.supports_follows_symlinks
.The following functions now support a file descriptor for their path argument:
chdir()
,chmod()
,chown()
,execve()
,listdir()
,pathconf()
,exists()
,stat()
,statvfs()
,utime()
. Platform supportfor this can be checked via theos.supports_fd
set.
access()
accepts aneffective_ids
keyword argument to turn onusing the effective uid/gid rather than the real uid/gid in the access check.Platform support for this can be checked via thesupports_effective_ids
set.The
os
module has two new functions:getpriority()
andsetpriority()
. They can be used to get or set processniceness/priority in a fashion similar toos.nice()
but extended to allprocesses instead of just the current one.(由 Giampaolo Rodolà 於bpo-10784 提交補丁。)
The new
os.replace()
function allows cross-platform renaming of afile with overwriting the destination. Withos.rename()
, an existingdestination file is overwritten under POSIX, but raises an error underWindows.(Contributed by Antoine Pitrou inbpo-8828.)The stat family of functions (
stat()
,fstat()
,andlstat()
) now support reading a file's timestampswith nanosecond precision. Symmetrically,utime()
can now write file timestamps with nanosecond precision. (Contributed byLarry Hastings inbpo-14127.)The new
os.get_terminal_size()
function queries the size of theterminal attached to a file descriptor. See alsoshutil.get_terminal_size()
.(Contributed by Zbigniew Jędrzejewski-Szmek inbpo-13609.)
New functions to support Linux extended attributes (bpo-12720):
getxattr()
,listxattr()
,removexattr()
,setxattr()
.New interface to the scheduler. These functionscontrol how a process is allocated CPU time by the operating system. Newfunctions:
sched_get_priority_max()
,sched_get_priority_min()
,sched_getaffinity()
,sched_getparam()
,sched_getscheduler()
,sched_rr_get_interval()
,sched_setaffinity()
,sched_setparam()
,sched_setscheduler()
,sched_yield()
,New functions to control the file system:
posix_fadvise()
: Announces an intention to access data in aspecific pattern thus allowing the kernel to make optimizations.posix_fallocate()
: Ensures that enough disk space is allocatedfor a file.sync()
: Force write of everything to disk.
其他新的 posix 函式:
lockf()
: Apply, test or remove a POSIX lock on an open file descriptor.pread()
: Read from a file descriptor at an offset, the fileoffset remains unchanged.pwrite()
: Write to a file descriptor from an offset, leavingthe file offset unchanged.readv()
: Read from a file descriptor into a number of writable buffers.truncate()
: Truncate the file corresponding topath, so thatit is at mostlength bytes in size.waitid()
: Wait for the completion of one or more child processes.writev()
: Write the contents ofbuffers to a file descriptor,wherebuffers is an arbitrary sequence of buffers.getgrouplist()
(bpo-9344): Return list of group ids thatspecified user belongs to.
times()
anduname()
: Return type changed from a tuple toa tuple-like object with named attributes.Some platforms now support additional constants for the
lseek()
function, such asos.SEEK_HOLE
andos.SEEK_DATA
.New constants
RTLD_LAZY
,RTLD_NOW
,RTLD_GLOBAL
,RTLD_LOCAL
,RTLD_NODELETE
,RTLD_NOLOAD
, andRTLD_DEEPBIND
are available onplatforms that support them. These are for use with thesys.setdlopenflags()
function, and supersede the similar constantsdefined inctypes
andDLFCN
. (Contributed by Victor Stinnerinbpo-13226.)os.symlink()
now accepts (and ignores) thetarget_is_directory
keyword argument on non-Windows platforms, to ease cross-platform support.
pdb¶
Tab-completion is now available not only for command names, but also theirarguments. For example, for thebreak
command, function and file namesare completed.
(由 Georg Brandl 在bpo-14210 中貢獻)
pickle¶
pickle.Pickler
objects now have an optionaldispatch_table
attribute allowing per-picklerreduction functions to be set.
(由 Richard Oudkerk 在bpo-14166 中貢獻。)
pydoc¶
The Tk GUI and theserve()
function have been removed from thepydoc
module:pydoc-g
andserve()
have been deprecatedin Python 3.2.
re¶
str
regular expressions now support\u
and\U
escapes.
(由 Serhiy Storchaka 在bpo-3665 中貢獻。)
sched¶
run()
now accepts ablocking parameter which whenset to false makes the method execute the scheduled events due to expiresoonest (if any) and then return immediately.This is useful in case you want to use thescheduler
innon-blocking applications. (Contributed by Giampaolo Rodolà inbpo-13449.)scheduler
class can now be safely used in multi-threadedenvironments. (Contributed by Josiah Carlson and Giampaolo Rodolà inbpo-8684.)timefunc anddelayfunct parameters of
scheduler
classconstructor are now optional and defaults totime.time()
andtime.sleep()
respectively. (Contributed by Chris Clark inbpo-13245.)enter()
和enterabs()
argument 參數現在是可選的。(由 Chris Clark 在bpo-13245 中貢獻。)enter()
和enterabs()
現在接受kwargs 參數。(由 Chris Clark 在bpo-13245 中貢獻。)
select¶
Solaris and derivative platforms have a new classselect.devpoll
for high performance asynchronous sockets via/dev/poll
.(Contributed by Jesús Cea Avión inbpo-6397.)
shlex¶
The previously undocumented helper functionquote
from thepipes
modules has been moved to theshlex
module anddocumented.quote()
properly escapes all characters in a stringthat might be otherwise given special meaning by the shell.
shutil¶
新功能:
disk_usage()
: provides total, used and free disk spacestatistics. (Contributed by Giampaolo Rodolà inbpo-12442.)chown()
: allows one to change user and/or group of the givenpath also specifying the user/group names and not only their numericids. (Contributed by Sandro Tosi inbpo-12191.)shutil.get_terminal_size()
: returns the size of the terminal windowto which the interpreter is attached. (Contributed by ZbigniewJędrzejewski-Szmek inbpo-13609.)
copy2()
andcopystat()
now preserve filetimestamps with nanosecond precision on platforms that support it.They also preserve file "extended attributes" on Linux. (Contributedby Larry Hastings inbpo-14127 andbpo-15238.)Several functions now take an optional
symlinks
argument: when thatparameter is true, symlinks aren't dereferenced and the operation insteadacts on the symlink itself (or creates one, if relevant).(Contributed by Hynek Schlawack inbpo-12715.)When copying files to a different file system,
move()
nowhandles symlinks the way the posixmv
command does, recreating thesymlink rather than copying the target file contents. (Contributed byJonathan Niehof inbpo-9993.)move()
now also returnsthedst
argument as its result.rmtree()
is now resistant to symlink attacks on platformswhich support the newdir_fd
parameter inos.open()
andos.unlink()
. (Contributed by Martin von Löwis and Hynek Schlawackinbpo-4489.)
signal¶
signal
模組有了新的函式:pthread_sigmask()
: fetch and/or change the signal mask of thecalling thread (Contributed by Jean-Paul Calderone inbpo-8407);pthread_kill()
:向執行緒發送訊號;sigpending()
:檢查未定的函式;sigwait()
:等待訊號;sigwaitinfo()
:等待訊號,回傳有關該訊號的詳細資訊;sigtimedwait()
:類似於sigwaitinfo()
但有超時。
The signal handler writes the signal number as a single byte instead ofa nul byte into the wakeup file descriptor. So it is possible to wait morethan one signal and know which signals were raised.
signal.signal()
和signal.siginterrupt()
會引發 OSError,而不是 RuntimeError:OSError 有一個 errno 屬性。
smtpd¶
Thesmtpd
module now supportsRFC 5321 (extended SMTP) andRFC 1870(size extension). Per the standard, these extensions are enabled if and onlyif the client initiates the session with anEHLO
command.
(InitialELHO
support by Alberto Trevino. Size extension by JuhanaJauhiainen. Substantial additional work on the patch contributed by MicheleOrrù and Dan Boswell.bpo-8739)
smtplib¶
TheSMTP
,SMTP_SSL
, andLMTP
classes now accept asource_address
keyword argumentto specify the(host,port)
to use as the source address in the bind callwhen creating the outgoing socket. (Contributed by Paulo Scardine inbpo-11281.)
SMTP
現在支援情境管理協議,允許在with
陳述式中使用SMTP
實例。(由 Giampaolo Rodolà 在bpo-11289 中貢獻。)
SMTP_SSL
構造函式和starttls()
方法現在接受 SSLContext 參數來控制安全通道的參數。(由 Kasun Herath 在bpo-8809 中貢獻。)
socket¶
當底層平台支援時,
socket
類現在公開了額外的方法來處理輔助資料:(由 David Watson 在bpo-6560 中貢獻,其基於 Heiko Wundram 的早期補丁)
socket
類別現在支援 Linux (https://lwn.net/Articles/253425) 上的 PF_CAN 協議系列 (https://en.wikipedia.org/wiki/Socketcan)。(在bpo-10141 中由 Matthias Fuchs 貢獻、並由 Tiago Gonçalves 更新。)
socket
類別現在支援 PF_RDS 協議系列(https://en.wikipedia.org/wiki/Reliable_Datagram_Sockets 和https://oss.oracle.com/projects/rds)。socket
類別現在支援 OS X 上的PF_SYSTEM
協議系列。(由 Michael Goderbauer 在bpo-13777 中貢獻。)New function
sethostname()
allows the hostname to be seton Unix systems if the calling process has sufficient privileges.(Contributed by Ross Lagerwall inbpo-10866.)
socketserver¶
BaseServer
now has an overridable methodservice_actions()
that is called by theserve_forever()
method in the service loop.ForkingMixIn
now uses this to clean up zombiechild processes. (Contributed by Justin Warkentin inbpo-11109.)
sqlite3¶
Newsqlite3.Connection
methodset_trace_callback()
can be used to capture a trace ofall sql commands processed by sqlite. (Contributed by Torsten Landschoffinbpo-11688.)
ssl¶
ssl
模組有兩個新的隨機生成函式:RAND_bytes()
:生成加密的強偽隨機位元組。RAND_pseudo_bytes()
:生成偽隨機位元組。
(由 Victor Stinner 在bpo-12049 中貢獻。)
The
ssl
module now exposes a finer-grained exception hierarchyin order to make it easier to inspect the various kinds of errors.(Contributed by Antoine Pitrou inbpo-11183.)load_cert_chain()
now accepts apassword argumentto be used if the private key is encrypted.(Contributed by Adam Simpkins inbpo-12803.)Diffie-Hellman key exchange, both regular and Elliptic Curve-based, isnow supported through the
load_dh_params()
andset_ecdh_curve()
methods.(Contributed by Antoine Pitrou inbpo-13626 andbpo-13627.)SSL sockets have a new
get_channel_binding()
methodallowing the implementation of certain authentication mechanisms such asSCRAM-SHA-1-PLUS. (Contributed by Jacek Konieczny inbpo-12551.)You can query the SSL compression algorithm used by an SSL socket, thanksto its new
compression()
method. The new attributeOP_NO_COMPRESSION
can be used to disable compression.(Contributed by Antoine Pitrou inbpo-13634.)Support has been added for the Next Protocol Negotiation extension usingthe
ssl.SSLContext.set_npn_protocols()
method.(Contributed by Colin Marc inbpo-14204.)SSL errors can now be introspected more easily thanks to
library
andreason
attributes.(Contributed by Antoine Pitrou inbpo-14837.)The
get_server_certificate()
function now supports IPv6.(Contributed by Charles-François Natali inbpo-11811.)New attribute
OP_CIPHER_SERVER_PREFERENCE
allows settingSSLv3 server sockets to use the server's cipher ordering preference ratherthan the client's (bpo-13635).
stat¶
The undocumented tarfile.filemode function has been moved tostat.filemode()
. It can be used to convert a file's mode to a string ofthe form '-rwxrwxrwx'.
(由 Giampaolo Rodolà 在bpo-14807 中貢獻。)
struct¶
Thestruct
module now supportsssize_t
andsize_t
via thenew codesn
andN
, respectively. (Contributed by Antoine Pitrouinbpo-3163.)
subprocess¶
Command strings can now be bytes objects on posix platforms. (Contributed byVictor Stinner inbpo-8513.)
A new constantDEVNULL
allows suppressing output in aplatform-independent fashion. (Contributed by Ross Lagerwall inbpo-5870.)
sys¶
Thesys
module has a newthread_info
namedtuple holding information about the thread implementation(bpo-11223).
tarfile¶
tarfile
現在透過lzma
模組支援lzma
編碼。(由 Lars Gustäbel 在bpo-5689 中貢獻。)
tempfile¶
tempfile.SpooledTemporaryFile
'struncate()
method now acceptsasize
parameter. (Contributed by Ryan Kelly inbpo-9957.)
textwrap¶
Thetextwrap
module has a newindent()
that makesit straightforward to add a common prefix to selected lines in a blockof text (bpo-13857).
threading¶
threading.Condition
,threading.Semaphore
,threading.BoundedSemaphore
,threading.Event
, andthreading.Timer
, all of which used to be factory functions returning aclass instance, are now classes and may be subclassed. (Contributed by ÉricAraujo inbpo-10968.)
Thethreading.Thread
constructor now accepts adaemon
keywordargument to override the default behavior of inheriting thedaemon
flagvalue from the parent thread (bpo-6064).
The formerly private function_thread.get_ident
is now available as thepublic functionthreading.get_ident()
. This eliminates several cases ofdirect access to the_thread
module in the stdlib. Third party code thatused_thread.get_ident
should likewise be changed to use the new publicinterface.
time¶
get_clock_info()
:取得時鐘資訊。monotonic()
:單調時鐘(不能倒退),不受系統時鐘更新的影響。perf_counter()
: Performance counter with the highest availableresolution to measure a short duration.process_time()
:目前行程的系統和使用者 CPU 時間總和。
其他新功能:
clock_getres()
、clock_gettime()
和clock_settime()
函式帶有CLOCK_xxx
常數。(由 Victor Stinner 在bpo-10278 中貢獻。)
To improve cross platform consistency,sleep()
now raises aValueError
when passed a negative sleep value. Previously this was anerror on posix, but produced an infinite sleep on Windows.
types¶
Add a newtypes.MappingProxyType
class: Read-only proxy of a mapping.(bpo-14386)
The new functionstypes.new_class()
andtypes.prepare_class()
provide supportforPEP 3115 compliant dynamic type creation. (bpo-14588)
unittest¶
assertRaises()
,assertRaisesRegex()
,assertWarns()
, andassertWarnsRegex()
now accept a keyword argumentmsg when used ascontext managers. (Contributed by Ezio Melotti and Winston Ewert inbpo-10775.)
unittest.TestCase.run()
現在回傳TestResult
物件。
urllib¶
TheRequest
class, now accepts amethod argumentused byget_method()
to determine what HTTP methodshould be used. For example, this will send a'HEAD'
request:
>>>urlopen(Request('https://www.python.org',method='HEAD'))
webbrowser¶
Thewebbrowser
module supports more "browsers": Google Chrome (namedchrome,chromium,chrome-browser orchromium-browser depending on the version and operating system),and the generic launchersxdg-open, from the FreeDesktop.orgproject, andgvfs-open, which is the default URI handler for GNOME3. (The former contributed by Arnaud Calmettes inbpo-13620, the latterby Matthias Klose inbpo-14493.)
xml.etree.ElementTree¶
Thexml.etree.ElementTree
module now imports its C accelerator bydefault; there is no longer a need to explicitly importxml.etree.cElementTree
(this module stays for backwards compatibility,but is now deprecated). In addition, theiter
family of methods ofElement
has been optimized (rewritten in C).The module's documentation has also been greatly improved with added examplesand a more detailed reference.
zlib¶
New attributezlib.Decompress.eof
makes it possible to distinguishbetween a properly formed compressed stream and an incomplete or truncated one.(Contributed by Nadeem Vawda inbpo-12646.)
New attributezlib.ZLIB_RUNTIME_VERSION
reports the version string ofthe underlyingzlib
library that is loaded at runtime. (Contributed byTorsten Landschoff inbpo-12306.)
最佳化¶
Major performance enhancements have been added:
Thanks toPEP 393, some operations on Unicode strings have been optimized:
the memory footprint is divided by 2 to 4 depending on the text
encode an ASCII string to UTF-8 doesn't need to encode characters anymore,the UTF-8 representation is shared with the ASCII representation
the UTF-8 encoder has been optimized
repeating a single ASCII letter and getting a substring of an ASCII stringis 4 times faster
UTF-8 is now 2x to 4x faster. UTF-16 encoding is now up to 10x faster.
建置和 C API 變更¶
Python 建置程序和 C API 的變更包括:
新的PEP 3118 相關功能:
PEP 393 added new Unicode types, macros and functions:
高階 API:
低階 API:
PyUnicode_DATA
,PyUnicode_1BYTE_DATA
,PyUnicode_2BYTE_DATA
,PyUnicode_4BYTE_DATA
PyUnicode_KIND
withPyUnicode_Kind
enum:PyUnicode_WCHAR_KIND
,PyUnicode_1BYTE_KIND
,PyUnicode_2BYTE_KIND
,PyUnicode_4BYTE_KIND
PyArg_ParseTuple
現在接受bytearray
為c
格式 (bpo-12380)。
已棄用¶
不支援的作業系統¶
由於缺乏維護者,OS/2 和 VMS 不再受支援。
Windows 2000 and Windows platforms which setCOMSPEC
tocommand.com
are no longer supported due to maintenance burden.
OSF 支援在 3.2 中已棄用,現已完全刪除。
已棄用的 Python 模組、函式和方法¶
Passing a non-empty string to
object.__format__()
is deprecated, andwill produce aTypeError
in Python 3.4 (bpo-9856).The
unicode_internal
codec has been deprecated because of thePEP 393, use UTF-8, UTF-16 (utf-16-le
orutf-16-be
), or UTF-32(utf-32-le
orutf-32-be
)platform.popen()
:使用subprocess
模組。請特別檢查Replacing Older Functions with the subprocess Module 部分 (bpo-11377)。bpo-13374: The Windows bytes API has been deprecated in the
os
module. Use Unicode filenames, instead of bytes filenames, to not depend onthe ANSI code page anymore and to support any filename.bpo-13988: The
xml.etree.cElementTree
module is deprecated. Theaccelerator is used automatically whenever available.The behaviour of
time.clock()
depends on the platform: use the newtime.perf_counter()
ortime.process_time()
function instead,depending on your requirements, to have a well defined behaviour.os.stat_float_times()
函式已棄用。abc
模組:importlib
套件:importlib.abc.SourceLoader.path_mtime()
is now deprecated in favour ofimportlib.abc.SourceLoader.path_stats()
as bytecode files now storeboth the modification time and size of the source file the bytecode file wascompiled from.
C API 中已棄用的函式和型別¶
Py_UNICODE
已被PEP 393 棄用,並將在 Python 4 中刪除。所有使用此型別的函式均已棄用:
Unicode functions and methods usingPy_UNICODE
andPy_UNICODE* types:
PyUnicode_FromUnicode
:使用PyUnicode_FromWideChar()
或PyUnicode_FromKindAndData()
PyUnicode_AS_UNICODE
、PyUnicode_AsUnicode()
、PyUnicode_AsUnicodeAndSize()
:使用PyUnicode_AsWideCharString()
PyUnicode_AS_DATA
:將PyUnicode_DATA
與PyUnicode_READ
和PyUnicode_WRITE
一起使用PyUnicode_GET_SIZE
、PyUnicode_GetSize()
:使用PyUnicode_GET_LENGTH
或PyUnicode_GetLength()
PyUnicode_GET_DATA_SIZE
:使用PyUnicode_GET_LENGTH(str)*PyUnicode_KIND(str)
(僅適用於準備好的字串)PyUnicode_AsUnicodeCopy()
:使用PyUnicode_AsUCS4Copy()
或PyUnicode_AsWideCharString()
PyUnicode_GetMax()
操作 Py_UNICODE* 字串的函式和巨集:
Py_UNICODE_strlen()
:使用PyUnicode_GetLength()
或PyUnicode_GET_LENGTH
Py_UNICODE_strcat()
:使用PyUnicode_CopyCharacters()
或PyUnicode_FromFormat()
Py_UNICODE_strcpy()
、Py_UNICODE_strncpy()
、Py_UNICODE_COPY()
:使用PyUnicode_CopyCharacters()
或PyUnicode_Substring()
Py_UNICODE_strcmp()
:使用PyUnicode_Compare()
Py_UNICODE_strncmp()
: 使用PyUnicode_Tailmatch()
Py_UNICODE_strchr()
,Py_UNICODE_strrchr()
: 使用PyUnicode_FindChar()
Py_UNICODE_FILL()
: 使用PyUnicode_Fill()
Py_UNICODE_MATCH
編碼器:
PyUnicode_Encode()
:使用PyUnicode_AsEncodedObject()
PyUnicode_EncodeUTF7()
PyUnicode_EncodeUTF8()
:使用PyUnicode_AsUTF8()
或PyUnicode_AsUTF8String()
PyUnicode_EncodeUTF32()
PyUnicode_EncodeUTF16()
PyUnicode_EncodeUnicodeEscape()
使用PyUnicode_AsUnicodeEscapeString()
PyUnicode_EncodeRawUnicodeEscape()
使用PyUnicode_AsRawUnicodeEscapeString()
PyUnicode_EncodeLatin1()
: 使用PyUnicode_AsLatin1String()
PyUnicode_EncodeASCII()
:使用PyUnicode_AsASCIIString()
PyUnicode_EncodeCharmap()
PyUnicode_TranslateCharmap()
PyUnicode_EncodeMBCS()
:使用PyUnicode_AsMBCSString()
或PyUnicode_EncodeCodePage()
(帶有CP_ACP
code_page)PyUnicode_EncodeDecimal()
、PyUnicode_TransformDecimalToASCII()
已棄用的功能¶
Thearray
module's'u'
format code is now deprecated and will beremoved in Python 4 together with the rest of the (Py_UNICODE
) API.
移植到 Python 3.3¶
本節列出了前面描述的更改以及可能需要你更改程式碼的其他錯誤修復。
移植 Python 程式碼¶
Hash randomization is enabled by default. Set the
PYTHONHASHSEED
environment variable to0
to disable hash randomization. See also theobject.__hash__()
method.bpo-12326: On Linux, sys.platform doesn't contain the major versionanymore. It is now always 'linux', instead of 'linux2' or 'linux3' dependingon the Linux version used to build Python. Replace sys.platform == 'linux2'with sys.platform.startswith('linux'), or directly sys.platform == 'linux' ifyou don't need to support older Python versions.
bpo-13847,bpo-14180:
time
anddatetime
:OverflowError
is now raised instead ofValueError
if atimestamp is out of range.OSError
is now raised if C functionsgmtime()
orlocaltime()
failed.The default finders used by import now utilize a cache of what is containedwithin a specific directory. If you create a Python source file or sourcelessbytecode file, make sure to call
importlib.invalidate_caches()
to clearout the cache for the finders to notice the new file.ImportError
now uses the full name of the module that was attempted tobe imported. Doctests that check ImportErrors' message will need to beupdated to use the full name of the module instead of just the tail of thename.Theindex argument to
__import__()
now defaults to 0 instead of -1and no longer support negative values. It was an oversight whenPEP 328 wasimplemented that the default value remained -1. If you need to continue toperform a relative import followed by an absolute import, then perform therelative import using an index of 1, followed by another import using anindex of 0. It is preferred, though, that you useimportlib.import_module()
rather than call__import__()
directly.__import__()
no longer allows one to use an index value other than 0for top-level modules. E.g.__import__('sys',level=1)
is now an error.Because
sys.meta_path
andsys.path_hooks
now have finders onthem by default, you will most likely want to uselist.insert()
insteadoflist.append()
to add to those lists.Because
None
is now inserted intosys.path_importer_cache
, if youare clearing out entries in the dictionary of paths that do not have afinder, you will need to remove keys paired with values ofNone
andimp.NullImporter
to be backwards-compatible. This will lead to extraoverhead on older versions of Python that re-insertNone
intosys.path_importer_cache
where it represents the use of implicitfinders, but semantically it should not change anything.importlib.abc.Finder
no longer specifies afind_module()
abstractmethod that must be implemented. If you were relying on subclasses toimplement that method, make sure to check for the method's existence first.You will probably want to check forfind_loader()
first, though, in thecase of working withpath entry finders.pkgutil
has been converted to useimportlib
internally. Thiseliminates many edge cases where the old behaviour of thePEP 302 importemulation failed to match the behaviour of the real import system. Theimport emulation itself is still present, but is now deprecated. Thepkgutil.iter_importers()
andpkgutil.walk_packages()
functionsspecial case the standard import hooks so they are still supported eventhough they do not provide the non-standarditer_modules()
method.A longstanding RFC-compliance bug (bpo-1079) in the parsing done by
email.header.decode_header()
has been fixed. Code that uses thestandard idiom to convert encoded headers into unicode(str(make_header(decode_header(h))
) will see no change, but code thatlooks at the individual tuples returned by decode_header will see thatwhitespace that precedes or followsASCII
sections is now included in theASCII
section. Code that builds headers usingmake_header
shouldalso continue to work without change, sincemake_header
continues to addwhitespace betweenASCII
and non-ASCII
sections if it is not alreadypresent in the input strings.email.utils.formataddr()
now does the correct content transferencoding when passed non-ASCII
display names. Any code that depended onthe previous buggy behavior that preserved the non-ASCII
unicode in theformatted output string will need to be changed (bpo-1690608).poplib.POP3.quit()
may now raise protocol errors like all otherpoplib
methods. Code that assumesquit
does not raisepoplib.error_proto
errors may need to be changed if errors onquit
are encountered by a particular application (bpo-11291).自 Python 2.4 以來已棄用的
email.parser.Parser
的strict
引數終於被刪除了。已棄用的方法
unittest.TestCase.assertSameElements
已被刪除。已棄用的變數
time.accept2dyear
已被刪除。The deprecated
Context._clamp
attribute has been removed from thedecimal
module. It was previously replaced by the public attributeclamp
. (Seebpo-8540.)The undocumented internal helper class
SSLFakeFile
has been removedfromsmtplib
, since its functionality has long been provided directlybysocket.socket.makefile()
.Passing a negative value to
time.sleep()
on Windows now raises anerror instead of sleeping forever. It has always raised an error on posix.The
ast.__version__
constant has been removed. If you need tomake decisions affected by the AST version, usesys.version_info
to make the decision.Code that used to work around the fact that the
threading
module usedfactory functions by subclassing the private classes will need to change tosubclass the now-public classes.The undocumented debugging machinery in the threading module has beenremoved, simplifying the code. This should have no effect on productioncode, but is mentioned here in case any application debug frameworks wereinteracting with it (bpo-13550).
Porting C code¶
In the course of changes to the buffer API the undocumented
smalltable
member of thePy_buffer
structure has been removed and thelayout of thePyMemoryViewObject
has changed.All extensions relying on the relevant parts in
memoryobject.h
orobject.h
must be rebuilt.Due toPEP 393, the
Py_UNICODE
type and allfunctions using this type are deprecated (but will stay available forat least five years). If you were using low-level Unicode APIs toconstruct and access unicode objects and you want to benefit of thememory footprint reduction provided byPEP 393, you have to convertyour code to the newUnicode API.However, if you only have been using high-level functions such as
PyUnicode_Concat()
,PyUnicode_Join()
orPyUnicode_FromFormat()
, your code will automatically takeadvantage of the new unicode representations.PyImport_GetMagicNumber()
現在在失敗時回傳-1
。As a negative value for thelevel argument to
__import__()
is nolonger valid, the same now holds forPyImport_ImportModuleLevel()
.This also means that the value oflevel used byPyImport_ImportModuleEx()
is now0
instead of-1
.
Building C extensions¶
The range of possible file names for C extensions has been narrowed.Very rarely used spellings have been suppressed: under POSIX, filesnamed
xxxmodule.so
,xxxmodule.abi3.so
andxxxmodule.cpython-*.so
are no longer recognized as implementingthexxx
module. If you had been generating such files, you haveto switch to the other spellings (i.e., remove themodule
stringfrom the file names).(於bpo-14040 中實作。)
命令列開關更改¶
The -Q command-line flag and related artifacts have been removed. Codechecking sys.flags.division_warning will need updating.
(由 Éric Araujo 於bpo-10998 中實作。)
Whenpython is started with
-S
,importsite
will no longer add site-specific paths to the module search paths. Inprevious versions, it did.(bpo-11591,由 Carl Meyer 貢獻並由 Éric Araujo 修訂。)