- Python 3.3 有什么新变化
- 摘要 — 发布重点
- PEP 405: 虚拟环境
- PEP 420: 隐式命名空间包
- PEP 3118: 新的内存视图实现和缓冲协议文档
- PEP 393: 灵活的字符串表示
- PEP 397: 适用于Windows的Python启动器
- PEP 3151: 重写 OS 和 IO 异常的层次结构
- PEP 380: 委托给子生成器的语法
- PEP 409: 清除异常上下文
- PEP 414: 显式的Unicode文本
- PEP 3155: 类和函数的限定名称
- PEP 412: Key-Sharing Dictionary
- PEP 362: 函数签名对象
- PEP 421: 添加 sys.implementation
- 使用 importlib 作为导入的实现
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
Python 3.3 有什么新变化
本文介绍了 Python 3.3 相比 3.2 的新增特性。 Python 3.3 于 2012 年 9 月 29 日 发布。 有关完整详细信息,请参见 changelog [https://docs.python.org/3.3/whatsnew/changelog.html]。
参见
PEP 398 [https://peps.python.org/pep-0398/] - Python 3.3 发布计划
摘要 — 发布重点
新的语法特性:
新的库模块:
faulthandler
(帮助调试低层级的崩溃)ipaddress
(代表 IP 地址和掩码的高层级对象)lzma
(使用 XZ / LZMA 算法压缩数据)unittest.mock
(使用模拟对象替换你的受测试系统中的某些部分)
新的内置特性:
- 重写 I/O 异常的层次结构.
实现的改进:
基于
importlib
重写 import machinery更紧凑的 Unicode 字符串。
更紧凑的 属性字典。
显著改进的库模块:
安全改进:
- 哈希随机化被默认启用。
请继续阅读有关面向用户的改变的详细清单。
PEP 405: 虚拟环境
虚拟环境有助于创建 独立的 Python 设置,同时共享全系统的基础安装,便于维护。 虚拟环境有自己的私有站点包(即本地安装的库),并可选择与系统范围的站点包分离。 虚拟环境的概念和实现 受到流行的virtualenv
第三方 包 的启发,但受益于与解释器 核心更紧密的集成。
本 PEP 添加了 venv
模块用于编程访问,以及 pyvenv
脚本用于命令在线访问和管理。 Python 解释器会检查 pyvenv.cfg
,文件的存在标志着虚拟环境目录树的基础。
参见
- PEP 405 [https://peps.python.org/pep-0405/] - Python虚拟环境
- PEP 由 Carl Meyer 撰写 ; 由 Carl Meyer 和 Vinay Sajip 实现。
PEP 420: 隐式命名空间包
原生支持不要求 __init__.py
标记文件和可以自动跨越多个路径节的包目录(灵感来自多个命名空间包的第三方方案,如 PEP 420 [https://peps.python.org/pep-0420/] 中所述)
参见
- PEP 420 [https://peps.python.org/pep-0420/] - 隐式命名空间包
- PEP 由 Eric V. Smith 撰写,由 Eric V. Smith 和 Barry Warsaw 实现
PEP 3118: 新的内存视图实现和缓冲协议文档
PEP 3118 [https://peps.python.org/pep-3118/] 的实现已获得大幅改进。
新的 memoryview 实现全面修复了 Py_buffer 结构体中曾导致多起崩溃报告的动态分配字段的所有权和生命周期问题。 此外,还修复了多个函数在非连续或多维输入时崩溃或返回不正确结果的问题。
现在 memoryview 对象具有符合 PEP-3118 标准的 getbufferproc(),可以检查使用者的请求类型。 新增了许多新的特性,其中的大部分已适用于非连续数组和带有子偏移量的数组。
文档已进行更新,清楚地列出了导出方和使用方的责任。 缓冲区请求旗标志被划分为基本旗标和复合旗标。 对非连续和多维的 NumPy 风格数组的内存布局进行了说明。
相关特性
现在 struct 模块语法中所有原生单字符格式指示符(可以选择添加 '@' 前缀)均受到支持。
在某些限制条件下,cast() 方法允许改变 C 连续数组的格式和形状。
任何数组类型都支持多维列表的表示形式。
任何数组类型都支持多维比较操作。
格式为 B、b 或 c 的可哈希(只读)类型的一维 memoryview 现在将是可哈希的。 (由 Antoine Pitrou 在 bpo-13411 [https://bugs.python.org/issue?@action=redirect&bpo=13411] 中贡献。)
支持对 1 维数据类型的任意切片。 例如,现在可以通过使用负步长值以 O(1) 复杂度对 memoryview 进行翻转。
API 的变化
官方的最大维度数量限制已更改为 64。
空形状、区间和子偏移量的表示形式现在是空元组而不是
None
。现在对格式为 'B' (无符号字节型) 的 memoryview 元素的访问将返回一个整数(遵循结构体模块语法)。 要返回字节串对象则必须先将视图强制转换为 'c'。
现在 memoryview 比较将使用操作数的逻辑结构并会按值来比较所有数组元素。 结构体模块语法中的所有格式化字符串均受到支持。 带有不可识别的格式化字符串的视图仍然被允许,但无论视图内容如何比较结果总是不相等。
更多改变请参阅 Build and C API Changes 和 Porting C code。
(由 Stefan Krah 在 bpo-10181 [https://bugs.python.org/issue?@action=redirect&bpo=10181] 中贡献。)
参见
PEP 3118 [https://peps.python.org/pep-3118/] - 修改缓冲区协议
PEP 393: 灵活的字符串表示
Unicode字符串类型已改为支持多种内部表示法,具体取决于所表示的字符串中具有最大 Unicode 序号(1、2 或 4 字节)的字符 。 这样,在常见情况下可以节省空间,但在所有系统上都能使用完整的 UCS-4。 对于使用现有应用程序接口的兼容性 来说,可能会并行存在几种表示法;随着时间的推移,这种兼容性 应逐步淘汰。
在 Python 一方,此项改变应当没有任何缺点。
在 C API 方面, PEP 393 [https://peps.python.org/pep-0393/] 完全向下兼容。 旧的 API 至少还能使用五年。 使用传统 API 的应用程序不会完全受益于内存的减少,或者更糟的是,可能会使用更多的内存,因为 Python 可能需要维护每个字符串的两个版本(传统格式和新的高效存储)。
功能
由 PEP 393 [https://peps.python.org/pep-0393/] 引入的改变如下:
Python 现在始终支持全部 Unicode 码位,包括非 BMP 码位 (即从
U+0000
到U+10FFFF
)。 窄编译版本和宽编译版本之间的区别已不复存在,Python 现在的行为就像宽编译版本,甚至在 Windows 下也是如此。随着窄编译版本的消亡,窄编译版本特有的问题也得到了解决,例如:
现在
len()
对于非 BMP 字符总是返回 1,因此len('\U0010FFFF') == 1
;替换对不会在字符串字面值中重新合并,因此
'\uDBFF\uDFFF' != '\U0010FFFF'
;索引或切分非 BMP 字符会返回预期的值,因此
'\U0010FFFF'[0]
现在会返回'\U0010FFFF'
而不是'\uDBFF'
;标准库中的所有其他函数现在都能正确处理非 BMP 代码点。
sys.maxunicode
的值现在总是1114111
(十六进制为0x10FFFF
)。PyUnicode_GetMax()
函数仍返回0xFFFF
或0x10FFFF
以便向下兼容,但不应与新的 Unicode API 一起使用 (参见 bpo-13054 [https://bugs.python.org/issue?@action=redirect&bpo=13054])。./configure
标志--with-wide-unicode
已被移除。
性能和资源使用情况
现在,Unicode 字符串的存储取决于字符串中的最高码位:
纯 ASCII 和 Latin1 字符串 (
U+0000-U+00FF
) 每个码位使用 1 个字节;BMP 字符串 (
U+0000-U+FFFF
) 每个码位使用 2 个字节;非 BMP 字符串 (
U+10000-U+10FFFF
) 每个码位使用 4 个字节。
这样做的效果是,对于大多数应用而言,字符串存储的内存使用量应该会大幅减少 —— 尤其是与以前的宽 unicode 版本相比 —— 因为在许多情况下,即使在国际环境中,字符串也将是纯 ASCII 格式(因为许多字符串存储的是非人类语言数据,如 XML 片段、HTTP 标头、JSON 编码数据等)。 出于同样的原因,我们还希望它能提高非小应用程序的 CPU 缓存效率。 在 Django 基准测试中,Python 3.3 的内存使用量比 Python 3.2 少两到三倍,比 Python 2.7 略好一些(详情请参见 PEP)。
参见
- PEP 393 [https://peps.python.org/pep-0393/] - 灵活的字符串表示
- PEP 由 Martin von Löwis 撰写 ; 由 Torsten Becker 和 Martin von Löwis 实现。
PEP 397: 适用于Windows的Python启动器
Python 3.3 的 Windows 安装程序现在包含一个 py
启动程序,可用于以版本无关的方式启动 Python 应用程序。
双击 *.py
文件时会隐式调用该启动器。 如果系统中只安装了一个 Python 版本,则将使用该版本运行文件。 如果安装了多个版本,则默认使用最新版本,但也可以通过在 Python 脚本中加入 Unix 风格的“shebang 行”来覆盖该版本。
启动器也可以作为 py
应用程序在命令行中显式使用。运行 py
遵循与隐式启动脚本相同的版本选择规则,但可以通过传递适当的参数来选择更具体的版本(例如,当 Python 2 也已安装时,使用 -3
来请求 Python 3;当安装了较新的 Python 版本时,使用 -2.6
来特别请求较早的 Python 版本)。
除了启动器之外,Windows 安装程序现在还包含一个选项,可将新安装的 Python 添加到系统 PATH 中。 (由 Brian Curtin 在 bpo-3561 [https://bugs.python.org/issue?@action=redirect&bpo=3561] 中贡献)。
参见
- PEP 397 [https://peps.python.org/pep-0397/] - 适用于Windows的Python启动器
- PEP 由 Mark Hammond 和 Martin v. Löwis 撰写 ; 由 Vinay Sajip实现。
启动器文档: 适用于Windows的Python启动器
安装器 PATH 修改: 查找Python可执行文件
PEP 3151: 重写 OS 和 IO 异常的层次结构
现在,由操作系统错误引发的异常层次结构既得到了简化,又更加精细。
您不必再为在 OSError
、IOError
、EnvironmentError
、WindowsError
、mmap.error
、socket.error
或 select.error
之间选择合适的异常类型而烦恼。 所有这些异常类型现在都只有一个: OSError
。 出于兼容性考虑,其他名称将作为别名保留。
此外,现在捕捉特定错误条件也更容易了。无需从 errno
模块中检查 errno
属性(或 args[0]
)中的特定常量,您可以捕捉适当的 OSError
子类。可用的子类如下:
并且 ConnectionError
本身具有细粒度的子类:
有了新的异常,现在就可以避免 errno
的常见用法了。 例如,下面是为 Python 3.2 编写的代码:
- from errno import ENOENT, EACCES, EPERM
- try:
- with open("document.txt") as f:
- content = f.read()
- except IOError as err:
- if err.errno == ENOENT:
- print("document.txt file is missing")
- elif err.errno in (EACCES, EPERM):
- print("You are not allowed to read document.txt")
- else:
- raise
现在无需导入 errno
,也无需手动检查异常属性:
- try:
- with open("document.txt") as f:
- content = f.read()
- except FileNotFoundError:
- print("document.txt file is missing")
- except PermissionError:
- print("You are not allowed to read document.txt")
参见
- PEP 3151 [https://peps.python.org/pep-3151/] - 重写 OS 和 IO 异常的层次结构
- PEP 由 Antoine Pitrou 撰写并实现
PEP 380: 委托给子生成器的语法
PEP 380 增加了 yield from
表达式,允许 generator 将其部分操作委托给另一个生成器。 这样,包含 yield
的代码部分就可以被分解出来,放在另一个生成器中。 此外,还允许子生成器返回一个值,并将该值提供给委托生成器。
虽然 yield from
表达式主要用于委托给子生成器,但它实际上允许委托给任意子生成器。
对于简单的迭代器而言,yield from iterable
本质上只是 for item in iterable: yield item
的简写形式:
- >>> def g(x):
- ... yield from range(x, 0, -1)
- ... yield from range(x)
- ...
- >>> list(g(5))
- [5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
However, unlike an ordinary loop, yield from
allows subgenerators to receive sent and thrown values directly from the calling scope, and return a final value to the outer generator:
- >>> def accumulate():
- ... tally = 0
- ... while 1:
- ... next = yield
- ... if next is None:
- ... return tally
- ... tally += next
- ...
- >>> def gather_tallies(tallies):
- ... while 1:
- ... tally = yield from accumulate()
- ... tallies.append(tally)
- ...
- >>> tallies = []
- >>> acc = gather_tallies(tallies)
- >>> next(acc) # Ensure the accumulator is ready to accept values
- >>> for i in range(4):
- ... acc.send(i)
- ...
- >>> acc.send(None) # Finish the first tally
- >>> for i in range(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 are designed to be used with the send
and throw
methods to be split into multiple subgenerators as easily as a single large function can be split into multiple subfunctions.
参见
- PEP 380 [https://peps.python.org/pep-0380/] - 委托给子生成器的语法
- PEP 由 Greg Ewing 撰写,由 Greg Ewing 实现。由 Renaud Blanch,Ryan Kelly 和 Nick Coghlan 集成到3.3,由 Zbigniew Jędrzejewski-Szmek 和 Nick Coghlan 编写文档
PEP 409: 清除异常上下文
PEP 409 introduces new syntax that allows the display of the chained exception context to be disabled. This allows cleaner error messages in applications that convert between exception types:
- >>> class D:
- ... def __init__(self, extra):
- ... self._extra_attributes = extra
- ... def __getattr__(self, attr):
- ... try:
- ... return self._extra_attributes[attr]
- ... except KeyError:
- ... raise AttributeError(attr) from None
- ...
- >>> D({}).x
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<stdin>", line 8, in __getattr__
- AttributeError: x
Without the from None
suffix to suppress the cause, the original exception would be displayed by default:
- >>> class C:
- ... def __init__(self, extra):
- ... self._extra_attributes = extra
- ... def __getattr__(self, attr):
- ... try:
- ... return self._extra_attributes[attr]
- ... except KeyError:
- ... raise AttributeError(attr)
- ...
- >>> C({}).x
- Traceback (most recent call last):
- File "<stdin>", line 6, in __getattr__
- KeyError: 'x'
- During handling of the above exception, another exception occurred:
- Traceback (most recent call last):
- File "<stdin>", line 1, in <module>
- File "<stdin>", line 8, in __getattr__
- AttributeError: x
No debugging capability is lost, as the original exception context remains available if needed (for example, if an intervening library has incorrectly suppressed valuable underlying details):
- >>> try:
- ... D({}).x
- ... except AttributeError as exc:
- ... print(repr(exc.__context__))
- ...
- KeyError('x',)
参见
- PEP 409 [https://peps.python.org/pep-0409/] - 清除异常上下文
- PEP 由 Ethan Furman 撰写 ,由 Ethan Furman 和 Nick Coghlan 实现。
PEP 414: 显式的Unicode文本
To ease the transition from Python 2 for Unicode aware Python applications that make heavy use of Unicode literals, Python 3.3 once again supports the "u
" prefix for string literals. This prefix has no semantic significance in Python 3, it is provided solely to reduce the number of purely mechanical changes in migrating to Python 3, making it easier for developers to focus on the more significant semantic changes (such as the stricter default separation of binary and text data).
参见
- PEP 414 [https://peps.python.org/pep-0414/] - 显式的Unicode文本
- PEP 由 Armin Ronacher 撰写
PEP 3155: 类和函数的限定名称
Functions and class objects have a new __qualname__
attribute representing the "path" from the module top-level to their definition. For global functions and classes, this is the same as __name__
. For other functions and classes, it provides better information about where they were actually defined, and how they might be accessible from the global scope.
Example with (non-bound) methods:
- >>> class C:
- ... def meth(self):
- ... pass
- ...
- >>> C.meth.__name__
- 'meth'
- >>> C.meth.__qualname__
- 'C.meth'
Example with nested classes:
- >>> class C:
- ... class D:
- ... def meth(self):
- ... pass
- ...
- >>> C.D.__name__
- 'D'
- >>> C.D.__qualname__
- 'C.D'
- >>> C.D.meth.__name__
- 'meth'
- >>> C.D.meth.__qualname__
- 'C.D.meth'
Example with nested functions:
- >>> def outer():
- ... def inner():
- ... pass
- ... return inner
- ...
- >>> outer().__name__
- 'inner'
- >>> outer().__qualname__
- 'outer.<locals>.inner'
The string representation of those objects is also changed to include the new, more precise information:
- >>> str(C.D)
- "<class '__main__.C.D'>"
- >>> str(C.D.meth)
- '<function C.D.meth at 0x7f46b9fe31e0>'
参见
- PEP 3155 [https://peps.python.org/pep-3155/] - 类和函数的限定名称
- PEP 由 Antoine Pitrou 撰写并实现
PEP 412: Key-Sharing Dictionary
Dictionaries used for the storage of objects' attributes are now able to share part of their internal storage between each other (namely, the part which stores the keys and their respective hashes). This reduces the memory consumption of programs creating many instances of non-builtin types.
参见
- PEP 412 [https://peps.python.org/pep-0412/] - Key-Sharing Dictionary
- PEP 由 Mark Shannon 撰写并实现。
PEP 362: 函数签名对象
A new function inspect.signature()
makes introspection of python callables easy and straightforward. A broad range of callables is supported: python functions, decorated or not, classes, and functools.partial()
objects. New classes inspect.Signature
, inspect.Parameter
and inspect.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 validates or amends calling signatures or arguments.
参见
- PEP 362 [https://peps.python.org/pep-0362/]: - 函数签名对象
- PEP 由 Brett Cannon,Yury Selivanov,Larry Hastings,Jiwon Seo 撰写,由 Yury Selivanov 实现
PEP 421: 添加 sys.implementation
A new attribute on the sys
module exposes details specific to the implementation of the currently running interpreter. The initial set of attributes on sys.implementation
are name
, version
, hexversion
, and cache_tag
.
The intention of sys.implementation
is to consolidate into one namespace the implementation-specific data used by the standard library. This allows different Python implementations to share a single standard library code base much more easily. In its initial state, sys.implementation
holds only a small portion of the implementation-specific data. Over time that ratio will shift in order to make the standard library more portable.
One example of improved standard library portability is cache_tag
. As of Python 3.3, sys.implementation.cache_tag
is used by importlib
to support PEP 3147 [https://peps.python.org/pep-3147/] compliance. Any Python implementation that uses importlib
for its builtin import system may use cache_tag
to control the caching behavior for modules.
SimpleNamespace
The implementation of sys.implementation
also introduces a new type to Python: types.SimpleNamespace
. In contrast to a mapping-based namespace, like dict
, SimpleNamespace
is attribute-based, like object
. However, unlike object
, SimpleNamespace
instances are writable. This means that you can add, remove, and modify the namespace through normal attribute access.
参见
- PEP 421 [https://peps.python.org/pep-0421/] - 添加 sys.implementation
- PEP 由 Eric Snow 撰写并实现
使用 importlib 作为导入的实现
bpo-2377 [https://bugs.python.org/issue?@action=redirect&bpo=2377] - Replace import w/ importlib.import bpo-13959 [https://bugs.python.org/issue?@action=redirect&bpo=13959] - Re-implement parts of imp
in pure Python bpo-14605 [https://bugs.python.org/issue?@action=redirect&bpo=14605] - Make import machinery explicit bpo-14646 [https://bugs.python.org/issue?@action=redirect&bpo=14646] - Require loaders set loader and package
The __import__()
function is now powered by importlib.__import__()
. This work leads to the completion of "phase 2" of PEP 302 [https://peps.python.org/pep-0302/]. There are multiple benefits to this change. First, it has allowed for more of the machinery powering import to be exposed instead of being implicit and hidden within the C code. It also provides a single implementation for all Python VMs supporting Python 3.3 to use, helping to end any VM-specific deviations in import semantics. And finally it eases the maintenance of import, allowing for future growth to occur.
For the common user, there should be no visible change in semantics. For those whose code currently manipulates import or calls import programmatically, the code changes that might possibly be required are covered in the Porting Python code section of this document.
新的API
One of the large benefits of this work is the exposure of what goes into making the import statement work. That means the various importers that were once implicit are now fully exposed as part of the importlib
package.
The abstract base classes defined in importlib.abc
have been expanded to properly delineate between meta path finders and path entry finders by introducing importlib.abc.MetaPathFinder
and importlib.abc.PathEntryFinder
, respectively. The old ABC of importlib.abc.Finder
is now only provided for backwards-compatibility and does not enforce any method requirements.
In terms of finders, importlib.machinery.FileFinder
exposes the mechanism used to search for source and bytecode files of a module. Previously this class was an implicit member of sys.path_hooks
.
For loaders, the new abstract base class importlib.abc.FileLoader
helps write a loader that uses the file system as the storage mechanism for a module's code. The loader for source files (importlib.machinery.SourceFileLoader
), sourceless bytecode files (importlib.machinery.SourcelessFileLoader
), and extension modules (importlib.machinery.ExtensionFileLoader
) are now available for direct use.
ImportError
now has name
and path
attributes which are set when there is relevant data to provide. The message for failed imports will also provide the full name of the module now instead of just the tail end of the module's name.
The importlib.invalidate_caches()
function will now call the method with the same name on all finders cached in sys.path_importer_cache
to help clean up any stored state as necessary.
可见的改变
For potential required changes to code, see the Porting Python code section.
Beyond the expanse of what importlib
now exposes, there are other visible changes to import. The biggest is that sys.meta_path
and sys.path_hooks
now store all of the meta path finders and path entry hooks used by import. Previously the finders were implicit and hidden within the C code of import instead of being directly exposed. This means that one can now 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 the loader used to create the module. PEP 302 [https://peps.python.org/pep-0302/] has been updated to make this attribute mandatory for loaders to implement, so in the future once 3rd-party loaders have been updated people will be able to rely on the existence of the attribute. Until such time, though, import is setting the module post-load.
Loaders are also now expected to set the __package__
attribute from PEP 366 [https://peps.python.org/pep-0366/]. Once again, import itself is already setting this on all loaders from importlib
and import itself is setting the attribute post-load.
None
is now inserted into sys.path_importer_cache
when no finder can be found on sys.path_hooks
. Since imp.NullImporter
is not directly exposed on sys.path_hooks
it could no longer be relied upon to always be available to use as a value representing no finder found.
All other changes relate to semantic changes which should be taken into consideration when updating code for Python 3.3, and thus should be read about in the Porting 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 [https://bugs.python.org/issue?@action=redirect&bpo=12753] 中贡献。)
Unicode 数据库更新至 UCD 版本 6.1.0
Equality comparisons on
range()
objects now return a result reflecting the equality of the underlying sequences generated by those range objects. (bpo-13201 [https://bugs.python.org/issue?@action=redirect&bpo=13201])The
count()
,find()
,rfind()
,index()
andrindex()
methods ofbytes
andbytearray
objects now accept an integer between 0 and 255 as their first argument.
(由 Petri Lehtinen 在 bpo-12170 [https://bugs.python.org/issue?@action=redirect&bpo=12170] 中贡献。)
The
rjust()
,ljust()
, andcenter()
methods ofbytes
andbytearray
now accept abytearray
for thefill
argument. (Contributed by Petri Lehtinen in bpo-12380 [https://bugs.python.org/issue?@action=redirect&bpo=12380].)New methods have been added to
list
andbytearray
:copy()
andclear()
(bpo-10516 [https://bugs.python.org/issue?@action=redirect&bpo=10516]). Consequently,MutableSequence
now also defines aclear()
method (bpo-11388 [https://bugs.python.org/issue?@action=redirect&bpo=11388]).Raw bytes literals can now be written
rb"…"
as well asbr"…"
.
(由 Antoine Pitrou 在 bpo-13748 [https://bugs.python.org/issue?@action=redirect&bpo=13748] 中贡献。)
dict.setdefault()
now does only one lookup for the given key, making it atomic when used with builtin types.
(由 Filip Gruszczyński 在 bpo-13521 [https://bugs.python.org/issue?@action=redirect&bpo=13521] 中贡献。)
- The error messages produced when a function call does not match the function signature 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 module would trigger code execution in a different thread as a side-effect. Clumsy workarounds were sometimes employed, such as the PyImport_ImportModuleNoBlock()
C API function.
In Python 3.3, importing a module takes a per-module lock. This correctly serializes importation of a given module from multiple threads (preventing the exposure of incompletely initialized modules), while eliminating the aforementioned annoyances.
(由 Antoine Pitrou 在 bpo-9260 [https://bugs.python.org/issue?@action=redirect&bpo=9260] 中贡献。)
Builtin functions and types
open()
gets a new opener parameter: the underlying file descriptor for the file object is then obtained by calling opener with (file, flags). It can be used to use custom flags likeos.O_CLOEXEC
for example. The'x'
mode was added: open for exclusive creation, failing if the file already exists.print()
: added the flush keyword argument. If the flush keyword argument 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 a casefolded copy of the string, casefolded strings may be used for caseless matching. For example,'ß'.casefold()
returns'ss'
.The sequence documentation has been substantially rewritten to better explain the binary/text sequence distinction and to provide specific documentation sections for the individual builtin sequence types (bpo-4966 [https://bugs.python.org/issue?@action=redirect&bpo=4966]).
新增模块
faulthandler
This new debug module faulthandler
contains functions to dump Python tracebacks explicitly, on a fault (a crash like a segmentation fault), after a timeout, or on a user signal. Call faulthandler.enable()
to install fault handlers for the SIGSEGV
, SIGFPE
, SIGABRT
, SIGBUS
, and SIGILL
signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER
environment variable or by using -X
faulthandler
command line option.
Linux 上的段错误示例:
- $ python -q -X faulthandler
- >>> import ctypes
- >>> ctypes.string_at(0)
- Fatal Python error: Segmentation fault
- Current thread 0x00007fb899f39700:
- File "homepython/cpython/Lib/ctypes/__init__.py", line 486 in string_at
- File "<stdin>", line 1 in <module>
- Segmentation fault
ipaddress
The new ipaddress
module provides tools for creating and manipulating objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e. an IP address associated with a specific IP subnet).
(由 Google 和 Peter Moody 在 bpo-3144 [https://bugs.python.org/issue?@action=redirect&bpo=3144] 中贡献。)
lzma
The newly added lzma
module provides data compression and decompression using the LZMA algorithm, including support for the .xz
and .lzma
file formats.
(由 Nadeem Vawda 和 Per Øyvind Karlsen 在 bpo-6715 [https://bugs.python.org/issue?@action=redirect&bpo=6715] 中贡献。)
改进的模块
abc
Improved support for abstract base classes containing descriptors composed with abstract methods. The recommended approach to declaring abstract descriptors is now to provide __isabstractmethod__
as a dynamically updated property. The builtin descriptors have been updated accordingly.
abc.abstractproperty
has been deprecated, useproperty
withabc.abstractmethod()
instead.abc.abstractclassmethod
has been deprecated, useclassmethod
withabc.abstractmethod()
instead.abc.abstractstaticmethod
has been deprecated, usestaticmethod
withabc.abstractmethod()
instead.
(由 Pablo Galindo 在 bpo-11610 [https://bugs.python.org/issue?@action=redirect&bpo=11610] 中贡献。)
abc.ABCMeta.register()
now returns the registered subclass, which means it can now be used as a class decorator (bpo-10868 [https://bugs.python.org/issue?@action=redirect&bpo=10868]).
array
The array
module supports the long long type using q
and Q
type codes.
(由 Oren Tirosh 和 Hirokazu Yamamoto 在 bpo-1172711 [https://bugs.python.org/issue?@action=redirect&bpo=1172711] 中贡献。)
base64
ASCII-only Unicode strings are now accepted by the decoding functions of the base64
modern interface. For example, base64.b64decode('YWJj')
returns b'abc'
. (Contributed by Catalin Iacob in bpo-13641 [https://bugs.python.org/issue?@action=redirect&bpo=13641].)
binascii
In addition to the binary objects they normally accept, the a2b_
functions now all also accept ASCII-only strings as input. (Contributed by Antoine Pitrou in bpo-13637 [https://bugs.python.org/issue?@action=redirect&bpo=13637].)
bz2
bz2
模块已被重新编写。 在此过程中,添加了一些新的特征:
新的
bz2.open()
函数:以二进制或文本模式打开 bzip2 压缩文件。bz2.BZ2File
现在可以读写任意文件型对象,具体方式是通过其构造器的 fileobj 参数。
(由 Nadeem Vawda 在 bpo-5863 [https://bugs.python.org/issue?@action=redirect&bpo=5863] 中贡献。)
bz2.BZ2File
andbz2.decompress()
can now decompress multi-stream inputs (such as those produced by the pbzip2 tool).bz2.BZ2File
can now also be used to create this type of file, using the'a'
(append) mode.
(由 Nir Aides 在 bpo-1625 [https://bugs.python.org/issue?@action=redirect&bpo=1625] 中贡献。)
bz2.BZ2File
now implements all of theio.BufferedIOBase
API, except for thedetach()
andtruncate()
methods.
编码器
The mbcs
codec has been rewritten to handle correctly replace
and ignore
error handlers on all Windows versions. The mbcs
codec now supports all error handlers, instead of only replace
to encode and ignore
to decode.
A new Windows-only codec has been added: cp65001
(bpo-13216 [https://bugs.python.org/issue?@action=redirect&bpo=13216]). It is the Windows code page 65001 (Windows UTF-8, CP_UTF8
). For example, it is used by sys.stdout
if the console output code page is set to cp65001 (e.g., using chcp 65001
command).
Multibyte CJK decoders now resynchronize faster. They only ignore the first byte of an invalid byte sequence. For example, b'\xff\n'.decode('gb2312',
'replace')
now returns a \n
after the replacement character.
(bpo-12016 [https://bugs.python.org/issue?@action=redirect&bpo=12016]) Incremental CJK codec encoders are no longer reset at each call to their encode() methods. For example:
- >>> import codecs
- >>> encoder = codecs.getincrementalencoder('hz')('strict')
- >>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
- b'{NpJ)l6HK!#} Bye.'
This example gives b'{Np}~{J)~}~{l6~}~{HK~}~{!#~} Bye.'
with older Python versions.
(bpo-12100 [https://bugs.python.org/issue?@action=redirect&bpo=12100]) unicode_internal
编解码器已被弃用。
collections
Addition of a new ChainMap
class to allow treating a number of mappings as a single unit. (Written by Raymond Hettinger for bpo-11089 [https://bugs.python.org/issue?@action=redirect&bpo=11089], made public in bpo-11297 [https://bugs.python.org/issue?@action=redirect&bpo=11297].) The abstract base classes have been moved in a new collections.abc
module, to better differentiate between the abstract and the concrete collections classes. Aliases for ABCs are still present in the collections
module to preserve existing imports. (bpo-11085 [https://bugs.python.org/issue?@action=redirect&bpo=11085]) The Counter
class now supports the unary +
and -
operators, as well as the in-place operators +=
, -=
, |=
, and &=
. (Contributed by Raymond Hettinger in bpo-13121 [https://bugs.python.org/issue?@action=redirect&bpo=13121].)
contextlib
ExitStack
now provides a solid foundation for programmatic manipulation of context managers and similar cleanup functionality. Unlike the previous contextlib.nested
API (which was deprecated and removed), the new API is designed to work correctly regardless of whether context managers acquire their resources in their __init__
method (for example, file objects) or in their __enter__
method (for example, synchronisation objects from the threading
module).
(bpo-13585 [https://bugs.python.org/issue?@action=redirect&bpo=13585])
crypt
Addition of salt and modular crypt format (hashing method) and the mksalt()
function to the crypt
module.
(bpo-10924 [https://bugs.python.org/issue?@action=redirect&bpo=10924])
curses
If the
curses
module is linked to the ncursesw library, use Unicode functions 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()
方法用来获取一个宽字符。curses
模块有一个新的unget_wch()
函数用来推入一个宽字符以便下一个get_wch()
将返回它。
(由 Iñigo Serna 在 bpo-6755 [https://bugs.python.org/issue?@action=redirect&bpo=6755] 中贡献。)
datetime
Equality comparisons between naive and aware
datetime
instances now returnFalse
instead of raisingTypeError
(bpo-15006 [https://bugs.python.org/issue?@action=redirect&bpo=15006]).New
datetime.datetime.timestamp()
method: Return POSIX timestamp corresponding to thedatetime
instance.The
datetime.datetime.strftime()
method supports formatting years older than 1000.The
datetime.datetime.astimezone()
method can now be called without arguments to convert datetime instance to the system timezone.
decimal
- bpo-7652 [https://bugs.python.org/issue?@action=redirect&bpo=7652] - integrate fast native decimal arithmetic.
- C-module and libmpdec written by Stefan Krah.
The new C version of the decimal module integrates the high speed libmpdec library for arbitrary precision correctly rounded decimal floating-point arithmetic. libmpdec conforms to IBM's General Decimal Arithmetic Specification.
Performance gains range from 10x for database applications to 100x for numerically intensive applications. These numbers are expected gains for standard precisions used in decimal floating-point arithmetic. Since the 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 available at https://www.bytereef.org/mpdecimal/quickstart.html.
decimal.py
_decimal
加速
pi
42.02秒
0.345秒
120倍
telco
172.19秒
5.68秒
30倍
psycopg
3.57秒
0.29秒
12倍
相关特性
The
FloatOperation
signal optionally enables stricter semantics for mixing floats and Decimals.If Python is compiled without threads, the C version automatically disables the expensive thread local context machinery. In this case, the variable
HAVE_THREADS
is set toFalse
.
API 的变化
- C模块上下文限制(如下表),具体取决于计算机体系结构:
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 observe the context limits and converts values with arbitrary exponents or precision exactly. Since the C version has internal limits, the following scheme is used: If possible, values are converted exactly, otherwiseInvalidOperation
is raised and the result is NaN. In the latter 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 the C 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
always refer to the sameMutableMapping
that the context was initialized with. If a new signal dictionary is assigned,flags
andtraps
are updated with the new values, but they do not reference the RHS dictionary.Pickling a
Context
produces a different output in order to have a common interchange format for the Python and C versions.The order of arguments in the
Context
constructor has been changed to match the order displayed byrepr()
.The
watchexp
parameter in thequantize()
method is deprecated.
Policy Framework
The email package now has a policy
framework. A Policy
is an object with several methods and properties that control how the email package behaves. The primary policy for Python 3.3 is the Compat32
policy, which provides backward compatibility with the email package in Python 3.2. A policy
can be specified when an email message is parsed by a parser
, or when a Message
object is created, or when an email is serialized using a generator
. Unless overridden, a policy passed to a parser
is inherited by all the Message
object and sub-objects created by the parser
. By default a generator
will use the policy of the Message
object it is serializing. The default policy is compat32
.
The minimum set of controls implemented by all policy
objects are:
max_line_length |
The maximum length, excluding the linesep character(s), individual lines may have when a Message is serialized. Defaults to 78.
|
linesep |
The character used to separate individual lines when a Message is serialized. Defaults to \n .
|
cte_type |
7bit or 8bit . 8bit applies only to a Bytes generator , and means that non-ASCII may be used where allowed by the protocol (or where it exists in the original input).
|
raise_on_defect |
导致一个 parser 在遇到缺陷时引发错误而不是将它们添加到 Message 对象的 defects 列表。
|
A new policy instance, with new settings, is created using the clone()
method of policy objects. clone
takes any of the above controls as keyword arguments. Any control not specified in the 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 by your application simpler. Instead of having to remember to specify linesep='\r\n'
in all the places you call a generator
, you can specify it once, when you set the policy used by the parser
or the Message
, whichever your program uses to create Message
objects. On the other hand, if you need to generate messages in multiple forms, you can still specify the parameters in the appropriate generator
call. Or you can have custom policy instances for your different cases, and pass those in when you create the generator
.
Provisional Policy with New Header API
While the policy framework is worthwhile all by itself, the main motivation for introducing it is to allow the creation of new policies that implement new features for the email package in a way that maintains backward compatibility for those who do not use the new policies. Because the new policies introduce a new API, we are releasing them in Python 3.3 as a provisional policy. Backwards incompatible changes (up to and including removal of the code) may occur if deemed necessary by the core developers.
The new policies are instances of EmailPolicy
, and add the following additional controls:
refold_source |
Controls whether or not headers parsed by a parser are refolded by the generator . It can be none , long , or all . The default is long , which means that source headers with a line longer than max_line_length get refolded. none means no line get refolded, and all means that all lines get refolded.
|
header_factory |
A callable that take a name and value and produces a custom header object.
|
The header_factory
is the key to the new features provided by the new policies. When one of the new policies is used, any header retrieved from a Message
object is an object produced by the header_factory
, and any time you set a header on a Message
it becomes an object produced by header_factory
. All such header objects have a name
attribute equal to the header name. Address and Date headers have additional attributes that give you access to the parsed data of the header. This means you can now do 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'].datetime
- datetime.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 as utf-8
when the message is serialized, but that when the header is accessed directly, you get the unicode version. This eliminates any need to deal with the email.header
decode_header()
or make_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 -0400
- cc: pals: Bob <bob@example.com>, Sally <sally@example.com>;, Bonzo <bonz@laugh.com>
Decoding to unicode is done automatically:
- >>> m2 = message_from_string(str(m))
- >>> m2['to']
- 'Éric <foo@example.com>'
When you parse a message, you can use the addresses
and groups
attributes of the header objects to access the groups and individual addresses:
- >>> 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 the way it ought to: your application works with unicode strings, and the email package transparently encodes and decodes the unicode to and from the RFC standard Content Transfer Encodings.
Other API Changes
New BytesHeaderParser
, added to the parser
module to complement HeaderParser
and complete the Bytes API.
New utility functions:
format_datetime()
: given adatetime
, produce a string formatted for use in an email header.parsedate_to_datetime()
: given a date string from an email header, convert it into an awaredatetime
, or a naivedatetime
if the offset is-0000
.localtime()
: With no argument, returns the current local time as an awaredatetime
using the localtimezone
. Given an awaredatetime
, converts it into an awaredatetime
using the localtimezone
.
ftplib
ftplib.FTP
now accepts asource_address
keyword argument to specify the(host, port)
to use as the source address in the bind call when creating the outgoing socket. (Contributed by Giampaolo Rodolà in bpo-8594 [https://bugs.python.org/issue?@action=redirect&bpo=8594].)The
FTP_TLS
class now provides a newccc()
function to revert control channel back to plaintext. This can be useful to take advantage of firewalls that know how to handle NAT with non-secure FTP without opening fixed ports. (Contributed by Giampaolo Rodolà in bpo-12139 [https://bugs.python.org/issue?@action=redirect&bpo=12139].)Added
ftplib.FTP.mlsd()
method which provides a parsable directory listing format and deprecatesftplib.FTP.nlst()
andftplib.FTP.dir()
. (Contributed by Giampaolo Rodolà in bpo-11072 [https://bugs.python.org/issue?@action=redirect&bpo=11072].)
functools
The functools.lru_cache()
decorator now accepts a typed
keyword argument (that defaults to False
to ensure that it caches values of different types that compare equal in separate cache slots. (Contributed by Raymond Hettinger in bpo-13227 [https://bugs.python.org/issue?@action=redirect&bpo=13227].)
gc
It is now possible to register callbacks invoked by the garbage collector before and after collection using the new callbacks
list.
hmac
A new compare_digest()
function has been added to prevent side channel attacks on digests through timing analysis. (Contributed by Nick Coghlan and Christian Heimes in bpo-15061 [https://bugs.python.org/issue?@action=redirect&bpo=15061].)