Python 3.4 有什么新变化

作者:

R. David Murray <rdmurray@bitdance.com> (Editor)

这篇文章介绍了 Python 3.4 相比 3.3 增加的新特性。 Python 3.4 发布于 2014 年 3 月 16 日。 对于完整的细节,请参见 更新日志

参见

PEP 429 -- Python 3.4 发布计划

摘要 - 发布重点

新的语法特性:

  • Python 3.4 中没有增加新的语法特性。

其他的新特性

新的库模块:

显著改进的库模块:

安全改进:

CPython 实现的改进:

请继续阅读有关针对用户的改变的完整清单,包括许多其他较小的改进、CPython 优化、弃用以及潜在的移植问题。

新的特性

PEP 453: 在 Python 安装版中对 PIP 的显式初始设置

默认对 pip 进行初始设置

新增的 ensurepip 模块(在 PEP 453 中定义)提供了一个在 Python 安装版和虚拟环境中初始设置 pip 安装器的标准跨平台机制。 包括在 Python 3.4.0 中的 pip 版本是 pip 1.5.4,未来的 3.4.x 维护发布版会将附带版本升级为创建候选发布版时的 pip 最新版本。

在默认情况下,将在所有平台上安装 pipXpipX.Y 等命令(其中 X.Y 表示 Python 安装包的版本),并包括 pip Python 包及其依赖。 在 Windows 中以及所有平台的虚拟环境中,还将安装不带版本号的 pip 命令。 在其他平台中,系统层级上不带版本号的 pip 命令通常是指向单独安装的 Python 2 版本。

pyvenv 命令行工具和 venv 模块可利用 ensurepip 模块在虚拟环境中准备好 pip。 当使用命令行工具时,会默认安装 pip,而当使用 venv 模块的 API 安装版时必须显式地安装 pip

对于 CPython 在 POSIX 系统上的源代码编译版make installmake altinstall 命令默认会初始设置 pip。 此行为可通过配置选项来控制,并通过 Makefile 选项来重写。

在 Windows 和 Mac OS X 上,现在 CPython 安装程序默认会将 pip 与 CPython 本身一同安装(用户可以在安装过程中选择不安装它)。 Window 用户需要选择执行 PATH 修改以使 pip 在命令行中默认可用,在其他情况下它仍然可以通过 Windows 版 Python 启动器以 py -m pip 的方式使用。

正如 在 PEP 中已讨论的,平台打包者可以选择默认不安装这些命令,只需要在它们被发起调用时,能够提供有关如何在该平台上安装它们的简单清晰的指引(通常是使用系统包管理器)。

备注

为了避免同时存在的 Python 2 和 Python 3 安装版之前的冲突,当 ensurepip 被直接发起调用时默认只会初始设置带版本号的 pip3pip3.4 命令 —— 需要添加 --default-pip 选项来请求设置不带版本号的 pip 命令。 pyvenv 和 Windows 安装程序会确保未限定版本的 pip 命令在环境中可用,并且 pip 始终可以通过 -m 选项开关而不是直接发起调用以避免在具有多个 Python 安装版的系统中造成歧义。

文档更改

作为此项更改的一部分,文档的 安装 Python 模块分发 Python 模块 章节已经完全重新设计,快速入门和 FAQ 文档也是如此。 大部分打包指南文档现在都已被移至由 Python Packaging Authority 维护的 Python Packaging User Guide 以及相应的独立项目文档。

不过,由于目前迁移过程尚未完成,这些指南的旧版本仍然可通过 使用 setuptools 构建 C 和 C++ 扩展使用 setuptools 构建 C 和 C++ 扩展 来访问。

参见

PEP 453 -- Python 安装版中对 pip 的显式初始设置

PEP 由Donald Stufft 和 Nick Coghlan 撰写,由 Donald Stufft,Nick Coghlan,Martin von Löwis 和 Ned Deily 实现。

PEP 446: 新创建的文件描述符将设为不可继承

PEP 446 将新创建的文件描述符设为 不可继承的。 通常,这就是应用程序所需要的行为:当启动一个新进程时,让当前打开的文件也在新进程里打开可能导致各种难以查找的程序错误以及潜在的安全问题。

不过,也存在一些需要继承行为的情况。 为了支持这些情况,可以使用以下的新增函数和方法:

参见

PEP 446 -- 将新创建的文件描述符设为不可继承

PEP 由 Victor Stinner 撰写并实现。

编解码器处理方式的改进

自首次被引入以来,codecs 模块始终是作为一个类型中立的动态编码和解码系统来运作的。 然而,它与 Python 文本模型,尤其是内置 strbytesbytearray 类型上的限定类型的便捷方法的紧密耦合,在历史上掩盖了这一事实。

作为明晰情况的关键一步,现在 codecs.encode()codecs.decode() 便捷函数在 Python 2.7、3.3 和 3.4 中都正确地写入了文档。 自 Python 2.4 以来这些函数即已存在于 codecs 模块中(并已被回归测试套件所覆盖),但在此前只能通过运行时自省才能发现。

不同于 str, bytesbytearray 上的便捷方法,codecs 的便捷函数同时支持 Python 2 和 Python 3 中的任意编解码器,而非仅限于 Unicode 文本编码格式(在 Python 3 中) 或 basestring <-> basestring 转换(在 Python 2 中)。

在 Python 3.4 中,解释器能够识别标准库中提供的已知非文本编码格式并会在适当的时候引导用户找到这些通用型便捷函数:

>>> b"abcdef".decode("hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.decode() to handle arbitrary codecs

>>> "hello".encode("rot13")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'rot13' is not a text encoding; use codecs.encode() to handle arbitrary codecs

>>> open("foo.txt", encoding="hex")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
LookupError: 'hex' is not a text encoding; use codecs.open() to handle arbitrary codecs

在相关的改变中,只要在不破坏向下兼容性 的情况下是可行的,则在编码和解码操作期间引发的异常都会被包装在一个特定类型的链式异常中,该类型的名称与产生错误的相应编解码器一致:

>>> import codecs

>>> codecs.decode(b"abcdefgh", "hex")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/hex_codec.py", line 20, in hex_decode
    return (binascii.a2b_hex(input), len(input))
binascii.Error: Non-hexadecimal digit found

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
binascii.Error: decoding with 'hex' codec failed (Error: Non-hexadecimal digit found)

>>> codecs.encode("hello", "bz2")
Traceback (most recent call last):
  File "/usr/lib/python3.4/encodings/bz2_codec.py", line 17, in bz2_encode
    return (bz2.compress(input), len(input))
  File "/usr/lib/python3.4/bz2.py", line 498, in compress
    return comp.compress(data) + comp.flush()
TypeError: 'str' does not support the buffer interface

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: encoding with 'bz2' codec failed (TypeError: 'str' does not support the buffer interface)

最后,正如上面的例子所示,这些改进允许恢复非 Unicode 编解码器的便捷别名,这些别名在 Python 3.2 中已被恢复。 这意味着(举例来说)二进制数据到其十六进制表示形式的编码转换现在可以写成:

>>> from codecs import encode, decode
>>> encode(b"hello", "hex")
b'68656c6c6f'
>>> decode(b"68656c6c6f", "hex")
b'hello'

在标准库中提供的二进制和文本转换操作详见 二进制转换文字转换

(由 Nick Coghlan 在 bpo-7475, bpo-17827, bpo-17828bpo-19619 中贡献。)

PEP 451: 针对导入系统的 ModuleSpec 类型

PEP 451 提供了对模块相关信息的封装,导入机制将使用这些信息来加载它(即模块规范说明)。 这有助于简化导入的实现和几个导入相关的 API。 这一改动也是 某些未来导入相关改进 的基石。

PEP 中面向公众的修改是完全向下兼容的。 并且,它们应当对除导入器开发者之外的其他所有人都可见。 主要查找器和加载器方法已被弃用,但它们将继续工作。 新的导入器应当使用 PEP 中描述的新方法。 现有的导入器应当被更新以实现这些新方法。 请参阅 弃用 一节获取应当被替代的方法及其替代物的列表。

其他语言特性修改

对Python 语言核心进行的小改动:

  • Unicode 数据库更新至 UCD 版本 6.3。

  • 现在 min()max() 均接受一个 default 仅限关键字参数可被用来指定当它们要求值的可迭代对象中没有任何元素时要返回的值。 (由 Julian Berman 在 bpo-18111 中贡献。)

  • 模块对象现在是 可弱引用的

  • 模块的 __file__ 属性(以及相关的值)现在应当总是默认包含绝对路径,唯一的例外是当使用相对路径直接执行一个脚本时的 __main__.__file__。 (由 Brett Cannon 在 bpo-18416 中贡献。)

  • 现在所有 UTF-* 编解码器(UTF-7 除外)在编码和解码期间都将拒绝替代符除非使用 surrogatepass 错误处理器,例外情况有 UTF-16 解码器(接受有效的替代符对)和 UTF-16 编码器(在编码非 BMP 字符时会产生替代符)。 (由 Victor Stinner, Kang-Hao (Kenny) Lu 和 Serhiy Storchaka 在 bpo-12892 中贡献。)

  • 新增 German EBCDIC 编解码器 cp273。 (由 Michael Bierenfeld 和 Andrew Kuchling 在 bpo-1097797 中贡献。)

  • 新增 Ukrainian 编解码器 cp1125。 (由 Serhiy Storchaka 在 bpo-19668 中贡献。)

  • 现在 bytes.join() 和 bytearray.join() 接受任意缓冲区对象作为参数。 (由 Antoine Pitrou 在 bpo-15958 中贡献。)

  • 现在 int 构造器接受任何具有 __index__ 方法的对象作为其 base 参数。 (由 Mark Dickinson 在 bpo-16772 中贡献。)

  • 帧对象现在具有 clear() 方法用来从帧中清除所有对局部变量的引用。 (由 Antoine Pitrou 在 bpo-17934 中贡献。)

  • 现在 memoryview 被注册为 序列,并支持 reversed() 内置函数。 (由 Nick Coghlan 和 Claudiu Popa 在 bpo-18690bpo-19078 中贡献。)

  • 作为对引入 Argument Clinic 以及对 inspectpydoc 模块的其他修改的结果,在各种场合下由 help() 所报告的签名信息已获得修改和提升。

  • 现在 __length_hint__() 已成为正式语言规范的一部分 (参见 PEP 424)。 (由 Armin Ronacher 在 bpo-16148 中贡献。)

新增模块

asyncio

新增的 asyncio 模块(在 PEP 3156 中定义)为 Python 提供了一个标准的可插入事件循环模型,在标准库中提供了坚实的异步 IO 支持,并使得其他事件循环的实现与标准库和其他库的相互操作更为容易。

对于 Python 3.4,此模块被视为属于 provisional API

参见

PEP 3156 -- 异步 IO 支持的重启: "asyncio" 模块

PEP 由 Guido van Rossum 领导编写和实现。

ensurepip

新增的 ensurepip 模块是用于 PEP 453 实现的主要基础设施。 在正常情况下最终用户不需要与此模块进行交互,但如果对安装版或虚拟环境的自动初始设置遭到拒绝则可使用它来手动初始设置 pip

ensurepip 包括了一个捆绑的 pip 副本,其版本更新时间即 CPython 发布包的第一个候选发布版的发布时间(此规则同样适用于维护发布版和新特性发布版)。 ensurepip 不会访问因特网。 如果安装版可以访问因特网,则在运行 ensurepip 之后可以使用所捆绑的 pip 来将 pip 升级为比所捆绑版本更高的版本。 (请注意这样得到的 pip 升级版本将被视为一个单独安装的软件包并且在 Python 被卸载时将不会被移除。)

该模块被命名为 ensurepip 是因为如果在已安装 pip 的情况下被调用,它将不做任何操作。 它还有一个 --upgrade 选项可以在当前已安装的 pip 版本比所捆绑的副本更旧的情况下安装所捆绑的 pip 副本。

enum

新增的 enum 模块(在 PEP 435 中定义)提供了枚举类型的标准实现,允许其他模块(如 socket 等)通过将含义不清晰的整数常量替换为可向下兼容的枚举值来提供更具信息量的错误消息和更好的调试支持。

参见

PEP 435 -- 为 Python 标准库增加了 Enum 类型

PEP 由 Barry Warsaw,Eli Bendersky 和 Ethan Furman 撰写 ,由 Ethan Furman 实现。

pathlib

新增的 pathlib 模块提供了代表文件系统路径的类,其语义适用于不同的操作系统。 路径类被划分为提供不带 I/O 的纯计算操作的 纯路径,以及继承自纯路径但提供 I/O 操作的 实体路径

对于 Python 3.4,此模块被视为属于 provisional API

参见

PEP 428 -- pathlib 模块 -- 面向对象的文件系统路径

PEP 由 Antoine Pitrou 撰写并实现

selectors

新增的 selectors 模块(作为 PEP 3156 实现的一部分被创建)允许高层级且高效的 I/O 多路复用,它是在 select 模块的基础上构建的。

statistics

新增的 statistics 模块(在 PEP 450 中定义)直接在标准库中提供了一些核心统计功能。 该模块支持计算数据系列的平均值、中位数、模式、方差和标准差等。

参见

PEP 450 -- 为标准库增加 statistics 模块

PEP 由 Steven D'Aprano 撰写并实现。

tracemalloc

新增的 tracemalloc 模块(在 PEP 454 中定义)是用于追踪由 Python 所分配的内存块的调试工具。 它提供了以下信息:

  • 追踪对象被分配所在的位置

  • 按文件、按行统计python的内存块分配情况: 总大小、块的数量以及块平均大小。

  • 对比两个内存快照的差异,以便排查内存泄漏

参见

PEP 454 -- 新增 tracemalloc 模块用于追踪 Python 内存分配

PEP 由 Victor Stinner 撰写并实现

改进的模块

abc

新增的函数 abc.get_cache_token() 可被用来获知何时使得受到对象图改变影响的缓存失效。 (由 Łukasz Langa 在 bpo-16832 中贡献。)

新增的类型 ABCABCMeta 作为其元类。 使用 ABC 作为基类的效果实际上相当于指定 metaclass=abc.ABCMeta,但其写法更简单也更易读。 (由 Bruno Dupuis 在 bpo-16049 中贡献。)

aifc

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-17818.)

aifc.open() now supports the context management protocol: when used in a with block, the close() method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchacha in bpo-16486.)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311.)

argparse

现在 FileType 类可接受 encodingerrors 参数,它们将被传递给 open()。 (由 Lucas Maystre 在 bpo-11175 中贡献。)

audioop

audioop now supports 24-bit samples. (Contributed by Serhiy Storchaka in bpo-12866.)

New byteswap() function converts big-endian samples to little-endian and vice versa. (Contributed by Serhiy Storchaka in bpo-19641.)

All audioop functions now accept any bytes-like object. Strings are not accepted: they didn't work before, now they raise an error right away. (Contributed by Serhiy Storchaka in bpo-16685.)

base64

现在 base64 中的编码和解码函数在之前需要 bytesbytearray 实例的场合下均接受任意 bytes-like object。 (由 Nick Coghlan 在 bpo-17839 中贡献。)

新增的函数 a85encode(), a85decode(), b85encode() 以及 b85decode() 分别提供针对 Ascii85 以及 git/mercurial Base85 格式的二进制数据进行编码和解码的能力。 a85 函数具有可被用于使其与 Ascii85 编码格式的变种,包括 Adobe 变种相互兼容的选项。 (由 Martin Morrison, Mercurial 项目, Serhiy Storchaka 和 Antoine Pitrou 在 bpo-17618 中贡献。)

collections

现在 ChainMap.new_child() 方法接受一个 m 参数用于指定要向链结构中添加的子映射表。 这允许将现有的映射和/或自定义映射类型用于子映射表。 (由 Vinay Sajip 在 bpo-16613 中贡献。)

colorsys

用于 RGB --- YIQ 转换系数的数码位数已被扩展以使其与 FCC NTSC 版本匹配。 结果中的变化应当少于 1% 并可与在其他地方找到的结果更好地匹配。 (由 Brian Landers 和 Serhiy Storchaka 在 bpo-14323 中贡献。)

contextlib

新增的 contextlib.suppress 上下文管理器可以帮助澄清故意抑制来自单条语句的异常的代码的意图。 (由 Raymond Hettinger 在 bpo-15806 和 Zero Piraeus 在 bpo-19266 中贡献。)

新增的 contextlib.redirect_stdout() 上下文管理器使得工具脚本能更容易地处理将输出写入 sys.stdout 并且不提供任何重定向选项的不灵活 API。 使用该上下文管理器,可以将 sys.stdout 的输出重定向到任何其他流,或者配合使用 io.StringIO 来重定向到字符串。 后一种方式有时会特别有用,例如写入函数的输出来实现 命令行接口。 由于它会影响 sys.stdout 的全局状态因此只推荐用于工具脚本。 (由 Raymond Hettinger 在 bpo-15805 中贡献。)

contextlib 文档也已获得更新以包括有关仅单用、可重用与可重入上下文管理器之间的区别的 讨论

dbm

现在 dbm.open() 对象已支持上下文管理器协议。 当在 with 语句中使用时,数据库对象的 close 方法将在代码块结束时被自动调用。 (由 Claudiu Popa 和 Nick Coghlan 在 bpo-19282 中贡献。)

dis

现在 show_code(), dis(), distb()disassemble() 等函数可接受仅限关键字参数 file 来控制其输出的写入目标。

现在 dis 模块是围绕 Instruction 类来构建的,该类以面向对象的访问方式提供对于每个单独字节码操作的细节。

新增的方法 get_instructions() 提供了一个为给定 Python 代码段产生 Instruction 流的迭代器。 这使得现在可以编写以不同于由 dis 模块本身所提供的方式检查和操纵字节码对象的程序。 例如:

>>> import dis
>>> for instr in dis.get_instructions(lambda x: x + 1):
...     print(instr.opname)
LOAD_FAST
LOAD_CONST
BINARY_ADD
RETURN_VALUE

dis 模块中的各种显示工具已被重新编写以使用这些新组件。

此外,新增的对应用程序友好的类 Bytecode 提供了一个面向对象的 API 用于以人类可读的形式检查字节码并对指令进行迭代。 Bytecode 构造器接受与 get_instruction() 相同的参数(外加一个可选的 current_offset 参数),其结果对象可被迭代以产生 Instruction 对象。 但它还有一个 dis 方法,相当于在构造器参数上调用 dis,但是返回一个多行字符串:

>>> bytecode = dis.Bytecode(lambda x: x + 1, current_offset=3)
>>> for instr in bytecode:
...     print('{} ({})'.format(instr.opname, instr.opcode))
LOAD_FAST (124)
LOAD_CONST (100)
BINARY_ADD (23)
RETURN_VALUE (83)
>>> bytecode.dis().splitlines()       
['  1           0 LOAD_FAST                0 (x)',
 '      -->     3 LOAD_CONST               1 (1)',
 '              6 BINARY_ADD',
 '              7 RETURN_VALUE']

Bytecode 还有一个类方法 from_traceback(),它提供了操纵回溯对象的能力(也就是说,print(Bytecode.from_traceback(tb).dis()) 等价于 distb(tb)。)

(由 Nick Coghlan, Ryan Kelly 和 Thomas Kluyver 在 bpo-11816 并由 Claudiu Popa 在 bpo-17916 中贡献。)

新增的函数 stack_effect() 可在给定操作码和参数的 Python 栈上计算其效果,相关信息是无法以其他方式获得的。 (由 Larry Hastings 在 bpo-19722 中贡献。)

doctest

新增的 选项旗标 FAIL_FAST 将在检测到首次失败时暂停测试运行。 (由 R. David Murray 和 Daniel Urban 在 bpo-16522 中贡献。)

现在 doctest 的命令行接口使用 argparse,并新增了两个选项 -o-f-o 允许在命令行中指定 doctest 选项,而 -f-o FAIL_FAST 的简写形式(与 unittest CLI 所支持的类似选项相对应)。 (由 R. David Murray 在 bpo-11390 中贡献。)

现在 doctest 会在扩展模块的 __doc__ 字符串中查找文档测试。 (由 Zachary Ware 在 bpo-3158 中贡献。)

email

现在 as_string() 接受一个 policy 参数用于在生成其字符串表示形式时重写默认的消息策略。 这意味着 as_string 现在可以在更多情况下被使用,而不必创建和使用 generator 来将已格式化的形参传递给其 flatten 方法。 (由 R. David Murray 在 bpo-18600 中贡献。)

新增方法 as_bytes() 用于产生消息的与 as_string 所产生的字符串表示形式类似的字节串表示形式。 它不接受 maxheaderlen 参数,但接受 unixfrompolicy 参数。 Message__bytes__() 方法将调用它,这意味着现在 bytes(mymsg) 将产生直观的结果:一个包含完整已格式化消息的字节串对象。 (由 R. David Murray 在 bpo-18600 中贡献。)

现在 Message.set_param() 消息接受一个 replace 关键字参数。 当指定该参数时,关联的标头将被更新而不会修改其在标头列表中的位置。 为了保持向下兼容,该参数默认值为 False。 (由 R. David Murray 在 bpo-18891 中贡献。)

新增了一对 Message 的子类 (EmailMessageMIMEPart),以及新的子模块 contentmanager 和新的 policy 属性 content_manager。 所有文档目前都在新模块中,它是作为 email 的新 provisional API 的一部分添加的。 这些类提供了多个使从内容提取邮件消息和插入内容到消息更容易的新方法。 相关细节,请参阅 contentmanager 文档和 email: 示例。 这些 API 的加入完成了作为 email6 项目计划组成部分的大部分工作。 目前的暂定 API 计划在 Python 3.5 最终确定 (可能在错误处理方面再增加少量内容)。 (由 R. David Murray 在 bpo-18891 中贡献。)

filecmp

新增的 clear_cache() 函数提供了清除 filecmp 比较缓存的功能,它使用 os.stat() 信息来确定文件自上次比较后是否发生了更改。 例如,如果文件被修改和重新检查的时间短于特定文件系统文件修改时间的精度就可使用这一功能。 (由 Mark Levitt 在 bpo-18149 中贡献。)

新增的模块属性 DEFAULT_IGNORES 提供了作为 dircmp() 函数的 ignore 形参默认值的目录列表。 (由 Eli Bendersky 在 bpo-15442 中贡献。)

functools

新增的 partialmethod() 描述器提供了对描述器的部分参数应用,就像 partial() 为普通可调用对象提供的一样。 新的描述器还可以让任意可调用对象 (包括 partial() 实例)在包括在类定义中时表现得像普通的实例方法一样。 (由 Alon Horev 和 Nick Coghlan 在 bpo-4331 中贡献。)

新增的 singledispatch() 装饰器为 Python 标准库带来了对单分派泛型函数的支持。 面向对象编程侧重于将对一组共同数据的多种操作组合到一个类中,而泛型函数则侧重于将一种操作的多个实现组合在一起使其能够处理 不同 种类的数据。

参见

PEP 443 -- 单分派泛型函数

PEP 由 Łukasz Langa 撰写并实现。

现在 total_ordering() 支持从下层的比较函数返回 NotImplemented 作为返回值。 (由 Katie Miller 在 bpo-10042 中贡献。)

现在标准库中增加了 partial() 函数的纯 Python 版本;在 CPython 中它会被 C 加速版本覆盖,但它以供其他实现来使用。 (由 Brian Thorne 在 bpo-12428 中贡献。)

gc

新增的函数 get_stats() 可返回由三个单独生成字典组成的列表,每个字典均包含自解释器启动以来收集的统计信息。 (由 Antoine Pitrou 在 bpo-16351 中贡献。)

glob

新增函数 escape() 提供了为文件名中的特殊字符进行转义的方式以使它们不会成为 glob 扩展的组成部分而是按字面值来匹配。 (由 Serhiy Storchaka 在 bpo-8402 中贡献。)

hashlib

新增的 hashlib.pbkdf2_hmac() 函数提供了 PKCS#5 基于口令的密钥派生函数 2。 (由 Christian Heimes 在 bpo-18582 中贡献。)

现在 hashlib 哈希对象的 name 属性已成为受正式支持的接口。 它一直存在于 CPython 的 hashlib 中(尽管它没有返回所有受支持的哈希算法的小写名称),但它不是一个公开的接口因此其他一些 Python 实现以前并不支持它。 (由 Jason R. Coombs 在 bpo-18532 中提供。)

hmac

现在 hmac 可接受 bytearraybytes 作为传给 new() 函数的 key 参数,而传给 new() 函数和 update() 方法的 msg 形参现在可接受 hashlib 模块所支持的任何类型。 (由 Jonas Borgström 的 bpo-18240 中贡献。)

传给 hmac.new() 函数的 digestmod 参数现在可以是 hashlib 能识别的任何哈希摘要名称。 此外,当前将 digestmod 默认值设为 MD5 的行为已被弃用:在未来的 Python 版本中将没有默认值。 (由 Christian Heimes 在 bpo-17276 中贡献。)

由于增加了 block_sizename 属性 (以及 digest_size 属性的正式文档),hmac 模块现在已完全符合 PEP 247 API。 (由 Christian Heimes 在 bpo-18775 中贡献。)

html

新增的函数 unescape() 用于将 HTML5 字符引用转换为相应的 Unicode 字符。 (由 Ezio Melotti 在 bpo-2927 中贡献。).)

HTMLParser 接受新的关键字参数 convert_charrefs,当其为 True 时,会自动转换所有字符引用。 为了保持向下兼容,其值默认为 False,但在未来的 Python 版本中将改为 True,因此建议你显式地设置它并更新代码以使用这个新特性。 (由 Ezio Melotti 在 bpo-13633 中贡献。)

现在 HTMLParserstrict 参数已被弃用。 (由 Ezio Melotti 在 bpo-15114 中贡献。)

http

现在 send_error() 接受可选的附加形参 explain 用于提供扩展的错误描述,覆盖可能存在的硬编码的默认值。 这个扩展的描述将使用 error_message_format 进行格式化并作为错误响应体发送。 (由 Karl Cow 在 bpo-12921 中贡献。)

现在 http.server 命令行界面 增加了一个 -b/--bind 选项用于让服务器在指定的地址上进行监听。 (由 Malte Swart 在 bpo-17764 中贡献。)

idlelib 与 IDLE

由于 idlelib 实现了 IDLE 命令行界面和编辑器且不应被其他程序导入,它将随每个发布版获得改进。 请参阅 Lib/idlelib/NEWS.txt 查看 3.3.0 以来的累积变化列表,以及未来 3.4.x 发布版即将发生的变化。 此文件也可通过 IDLE Help ‣ About IDLE 对话框来查看。

importlib

InspectLoader ABC 定义了一个新方法 source_to_code(),它接受源数据和一个路径并返回一个代码对象。 其默认实现等价于 compile(data, path, 'exec', dont_inherit=True)。 (由 Eric Snow 和 Brett Cannon 在 bpo-15627 中贡献。)

现在 InspectLoader 也具有 get_code() 方法的默认实现。 不过,出于性能原因通常需要重写默认实现。 (由 Brett Cannon 在 bpo-18072 中贡献。)

由于 imp 模块被弃用 reload() 函数已从 imp 移至 importlib。 (由 Berker Peksag 在 bpo-18193 中贡献。)

现在 importlib.util 具有一个 MAGIC_NUMBER 属性用来提供字节码版本号信息。 它替换了已弃用的 imp 模块中的 get_magic() 函数。 (由 Brett Cannon 在 bpo-18192 中贡献。)

新增的 importlib.util 函数 cache_from_source()source_from_cache() 替换了已弃用的 imp 模块中的同名函数。 (由 Brett Cannon 在 bpo-18194 中贡献。)

现在 importlib 将以符合 InspectLoader ABC 的方式初始设置 NamespaceLoader,这意味着 runpy `` 和``python -m 现在可以与命名空间包一起使用。 (由 Brett Cannon 在 bpo-18058 中贡献。)

importlib.util 中新增的函数 decode_source() 可使用通用换行处理方式从字节数据中解码源代码。 这适用于实现 InspectLoader.get_source() 方法。

现在 importlib.machinery.ExtensionFileLoader 增加了 get_filename() 方法。 此方法在最初的实现中意外缺失。 (由 Eric Snow 在 bpo-19152 中贡献。)

inspect

现在 inspect 模块提供了一个基本的 命令行界面 用于快速显示模块、类和函数的源代码以及其他信息。 (由 Claudiu Popa 和 Nick Coghlan 在 bpo-18626 中贡献。)

unwrap() 用于方便地解开由 functools.wraps() (以及任何在包装器函数上设置 __wrapped__ 属性的 API) 创建的包装器函数链。 (由 Daniel Urban, Aaron Iles 和 Nick Coghlan 在 bpo-13266 中贡献。)

作为新的 enum 模块实现的一部分,现在 inspect 模块通过元类为自定义 __dir__ 方法和动态类属性提供了更好的支持。 (由 Ethan Furman 在 bpo-18929bpo-19030 中贡献。)

现在 getfullargspec()getargspec() 将使用 signature() API。 这允许它们支持更多种类的可调用对象,包括具有 __signature__ 属性的、具有通过 argument clinic 提供元数据的、functools.partial() 对象等等。 请注意,不同于 signature(),这些函数仍然会忽略 __wrapped__ 属性,并会报告绑定方法已绑定的第一个参数,所以如果想要这些特性的话你仍然需要更新你的代码以直接使用 signature()。 (由 Yury Selivanov 在 bpo-17481 中贡献。)

现在 signature() 支持 CPython 函数的鸭子类型,它增加了对使用 Cython 编译的函数的支持。 (由 Stefan Behnel 和 Yury Selivanov 在 bpo-17159 中贡献。)

ipaddress

ipaddress 已在 Python 3.3 中作为 provisional API 被添加到标准库。 随着 Python 3.4 的发布,此限定已被移除:现在 ipaddress 属于稳定 API,由常规的标准库需求所覆盖以维护向下兼容性。

如果一个地址是全局可路由的则新增的 is_global 属性将为 True。 (由 Peter Moody 在 bpo-17400 中贡献。)

logging

TimedRotatingFileHandler 新增的 atTime 形参可被用于指定每日要执行日志文件轮转的时间。 (由 Ronald Oussoren 在 bpo-9556 中贡献。)

现在 SocketHandlerDatagramHandler 已支持 Unix 域套接字 (通过将 port 设为 None)。 (由 Vinay Sajip 在 commit ce46195b56a9 中贡献。)

现在 fileConfig() 接受一个 configparser.RawConfigParser 子类实例作为 fname 形参。 这有助于在日志配置只是整体应用程序配置的一部分,或者在将配置传递给 fileConfig() 之前对其进行了修改时使用配置文件。 (由 Vinay Sajip 在 bpo-16110 中贡献。)

现在通过 logging.config.listen() 函数从套接字接收的日志配置数据可以在处理前以将验证函数作为参数提供给新的 verify 关键字参数 的方式执行验证。 (由 Vinay Sajip 在 bpo-15452 中贡献。)

marshal

默认的 marshal 版本已被提升至 3。 新版本的代码实现恢复了 Python2 行为即只记录内联字符串的一份副本并在反序列化时保留内联状态,并将此“一份副本”功能扩展到任何对象类型(包括处理递归引用)。 这既减少了 .pyc 文件的大小也减少了模块从 .pyc (或``.pyo``) 文件加载时占用的内存量。 (由 Kristján Valur Jónsson 在 bpo-16475 中贡献,并由 Antoine Pitrou 在 bpo-19219 中提供进一步的加速。)

mmap

现在 mmap 对象将是 可弱引用的。 (由 Valerie Lambert 在 bpo-4885 中贡献。)

multiprocessing

在 Unix 上新增了两个 启动方法 spawnforkserver 可使用 multiprocessing 来启动进程。 这两个方法使得进程和线程的混合更为健壮,并且 spawn 方法可以匹配 multiprocessing 在 Windows 上一直使用的语法。 新增的函数 get_all_start_methods() 可报告平台上可用的所有启动方法,get_start_method() 可报告当前的启动方法,而 set_start_method() 可设置启动方法。 (由 Richard Oudkerk 在 bpo-8713 中贡献。)

现在 multiprocessing 还具有 上下文 的概念,它决定了子进程的创建方式。 新增的函数 get_context() 可返回一个使用指定启动方法的上下文。 它具有与 multiprocessing 模块本身一致的 API,因此你可以使用它来创建 Pool 和其他在上下文中执行操作的对象。 这允许一个框架和某个应用程序或相同应用程序的不同部分使用多进程而不会彼此干扰。 (由 Richard Oudkerk 在 bpo-18999 中贡献。)

除非是在使用旧的 fork 启动方法,子进程将不再从其父进程继承不需要的句柄/文件描述符 (bpo-8713 的一部分)。

现在当使用 spawnforkserver 启动方法时 multiprocessing 依赖于 runpy (它实现了 -m 开关) 在子进程中正确地初始化 __main__。 这解决了一些合并多进程操作中,-m 命令行开关和显式相对导入可能在子进程中导致失败的边缘场景问题。 (由 Nick Coghlan 在 bpo-19946 中贡献。)

operator

新增的函数 length_hint() 提供了应当如何使用 __length_hint__() 特殊方法的规范实现,作为该语言特性的 PEP 424 正式规范说明的一部分。 (由 Armin Ronacher 在 bpo-16148 中贡献。)

现在提供了一个纯 Python 版本的 operator 模块,可用于参考并由 Python 的其他实现使用。 (由 Zachary Ware 在 bpo-16694 中贡献。)

os

新增一些函数用于获取和设置文件描述符或 Windows 句柄的 可继承旗标 (os.get_inheritable(), os.set_inheritable()) 或 (os.get_handle_inheritable(), os.set_handle_inheritable())。

新增函数 cpu_count() 可报告 Python 运行所在平台上可用 CPU 的数量 (如果无法确定数量则为 None)。 现在 multiprocessing.cpu_count() 函数是根据此函数实现的。 (由 Trent Nelson, Yogesh Chaudhari, Victor Stinner 和 Charles-François Natali 在 bpo-17914 中贡献。)

现在 os.path.samestat() 将在 Windows 平台上可用(并且现在 os.path.samefile() 实现可在 Unix 和 Windows 间共享)。 (由 Brian Curtin 在 bpo-11939 中贡献。)

现在 os.path.ismount() 可识别 Windows 中在驱动器根目录下加载的卷。 (由 Tim Golden 在 bpo-9035 中贡献。)

os.open() 在受支持的平台上提供了两个新旗标 O_PATH (未打开的文件描述符) 和 O_TMPFILE (未命名的临时文件;因为 3.4.0 发布版仅在具有 uapi 标头的内核版本 3.11 或更新的 Linux 系统上可用)。 (分别由 Christian Heimes 在 bpo-18673 中以及 Benjamin Peterson 贡献。)

pdb

pdb 已被增强以通过更有用的方式来处理生成器, yieldyield from。 这在调试基于 asyncio 的程序时特别有帮助。 (由 Andrew Svetlov 和 Xavier de Gaye 在 bpo-16596 中贡献。)

print 命令已从 pdb 中移除,恢复了从 pdb 命令行对 Python print() 函数的访问。 Python2 的 pdb 没有 print 命令;而是会在输入 print 时执行 print 语句。 在 Python3 中 print 被错误地设为 pdb p 命令的别名。 然而,p 会打印其参数的 repr,而不是像 Python2 print 命令那样打印其参数的 str。 更糟糕的是,Python3 pdb print 命令会覆盖 Python3 print 函数,导致其在 pdb 提示符下无法被访问。 (由 Connor Osborn 在 bpo-18764 中贡献。)

pickle

现在 pickle 支持(但默认不使用)新的 pickle 协议即协议 4。 这个新协议解决了在之前版本中存在的多个问题,例如嵌套类、超长字符串和容器、以及 __new__() 方法接受仅限关键字参数的类的序列化。 它还提供了一些效率上的改进。

参见

PEP 3154 -- pickle 协议 4

PEP 由 Antoine Pitrou 撰写,并由 Alexandre Vassalotti 实现

plistlib

现在 plistlib 个具有与 stdlib 序列化协议标准模式类似的 API,使用新的 load(), dump(), loads()dumps() 函数。 (旧 API 现已被弃用。) 除了已受支持的 XML plist 格式 (FMT_XML),现在它还支持二进制 plist 格式 (FMT_BINARY)。 (由 Ronald Oussoren 等人在 bpo-14455 中贡献。)

poplib

poplib 中新增了两个方法: capa(),它将返回 POP 服务器公开的功能列表,以及 stls(),它将在 POP 支持的情况下将明文 POP3 会话切换为加密 POP3 会话。 (由 Lorenzo Catucci 在 bpo-4473 中贡献。)

pprint

pprint 模块的 PrettyPrinter 类以及 pformat()pprint() 函数新增了一个选项 compact,它可控制输出所使用的格式。 目前将 compact 设为 True 表示打印序列时将在每个(缩进的)行中放入 width 所允许的尽可能多的元素。 (由 Serhiy Storchaka 在 bpo-19132 中贡献。)

长字符串现在将使用 Python 的常规续行语法进行包装。 (由 Antoine Pitrou 在 bpo-17150 中贡献。)

pty

现在 pty.spawn() 将返回来自子进程上 os.waitpid() 的状态值,而不是 None。 (由 Gregory P. Smith 贡献。)

pydoc

现在 pydoc 模块是直接基于 inspect.signature() 内省 API,这允许它提供更多可调用对象的签名信息。 这一改变也意味着现在当显示帮助信息时 __wrapped__ 属性也会被纳入考虑。 (由 Larry Hastings 在 bpo-19674 中贡献。)

pydoc 模块将不再显示已绑定方法的 self 形参。 现在,它总是会显示所提供可调用对象实际的当前签名。 (由 Larry Hastings 在 bpo-20710 中贡献。)

除了 pydoc 已有的直接修改,它对自定义 __dir__ 方法和各种描述器行为的处理也通过对下层 inspect 模块的修改获得了显著的改进。

由于 help() 内置函数是基于 pydoc 的,上述的变化也会影响 help() 的行为。

re

新增的 fullmatch() 函数和 regex.fullmatch() 方法可将模式锚定到要匹配的字符串的两端。 这提供了一种明确匹配目标的方式,从而避免了一类微妙的错误错误,即在代码更改或为现有正则表达式添加替代项时丢失 $ 字符。 (由 Matthew Barnett 在 bpo-16203 中贡献。)

正则表达式对象 的 repr 现在将包括模式和旗标;匹配对象 的 repr 现在将包括已匹配字符串的开头、末尾和组成。 (由 Hugo Lopes Tavares 和 Serhiy Storchaka 在 bpo-13592bpo-17087 中贡献。)

resource

新增的 prlimit() 函数,在内核版本 2.6.36 以上的 Linux 平台及 glibc 版本 2.13 以上可用,提供了查询或设置执行调用的进程以外的进程的资源限制的功能。 (由 Christian Heimes 在 bpo-16595 中贡献。)

在内核版本 2.6.36 以上的 Linux 上,新增了一些 Linux 专属的常量: RLIMIT_MSGQUEUE, RLIMIT_NICE, RLIMIT_RTPRIO, RLIMIT_RTTIMERLIMIT_SIGPENDING。 (由 Christian Heimes 在 bpo-19324 中贡献。)

在版本 9 以上的 FreeBSD 上,新增了一些 FreeBSD 专属的常量: RLIMIT_SBSIZE, RLIMIT_SWAPRLIMIT_NPTS。 (由 Claudiu Popa 在 bpo-19343 中贡献。)

select

现在 epoll 对象可支持上下文管理协议。 当在 with 语句中使用时,close() 方法将在代码块结束时被自动调用。 (由 Serhiy Storchaka 在 bpo-16488 中贡献。)

现在 devpoll 对象具有 fileno()close() 方法,以及新的属性 closed。 (由 Victor Stinner 在 bpo-18794 中贡献。)

shelve

现在 Shelf 实例可以在 with 语句中使用,并将在 with 代码块结束时自动关闭。 (由 Filip Gruszczyński 在 bpo-13896 中贡献。)

shutil

现在当源和目标为相同文件时 copyfile() 会引发专门的 Error 子类 SameFileError,这允许应用程序针对这个特定错误采取适当的动作。 (由 Atsuo Ishimoto 和 Hynek Schlawack 在 bpo-1492704 中贡献。)

smtpd

现在 SMTPServerSMTPChannel 类接受一个 map 关键字参数,如果指定了该参数,它将被传给 asynchat.async_chat 作为其 map 参数。 这允许应用程序避免影响全局套接字映射表。 (由 Vinay Sajip 在 bpo-11959 中贡献。)

smtplib

现在 SMTPExceptionOSError 的子类,它允许仅需关注是否有错误发生的代码在一个 try/except 语句中同时捕获套接字级错误和 SMTP 协议级错误。 (由 Ned Jackson Lovely 在 bpo-2118 中贡献。)

socket

现在 socket 模块会在受支持的平台上支持 CAN_BCM 协议。 (由 Brian Thorne 在 bpo-15359 中贡献。)

Socket 对象新增了用于获取或设置其 可继承旗标 的方法,get_inheritable()set_inheritable()

现在 socket.AF_*socket.SOCK_* 常量是使用了新增的 enum 模块的枚举值。 这允许在调试期间打印有意义的名称,而不是整数形式的“魔法数字”。

现在 AF_LINK 常量将在 BSD 和 OSX 上可用。

现在 inet_pton()inet_ntop() 在 Windows 上已受到支持。 (由 Atsuo Ishimoto 在 bpo-7171 中贡献。)

sqlite3

connect() 函数新增布尔值形参 uri,它可被用来指明 database 形参是一个 uri (参见 SQLite URI 文档)。 (由 poq 在 bpo-13773 中贡献。)

ssl

添加了 PROTOCOL_TLSv1_1PROTOCOL_TLSv1_2 (TLSv1.1 和 TLSv1.2 支持);对这些协议的支持仅在 Python 使用 OpenSSL 1.0.1 或更高版本链接时可用。 (由 Michele Orrù 和 Antoine Pitrou 在 bpo-16692 中贡献。)

新增的函数 create_default_context() 提供了获取 SSLContext 的标准方式,其设置旨在合理兼顾兼容性和安全性。 这些设置比 SSLContext 构造器所提供的默认设置更为严格,如果最佳实践的安全要求发生变化,将来可能会对其进行调整,而不预先提示弃用。 对于使用支持 SSL 的 stdlib 库来新推荐的最佳实践是使用 create_default_context() 来获取 SSLContext 对象,必要时对其进行修改,然后将其作为相应 stdlib API 的 contex 参数传入。 (由 Christian Heimes 在 bpo-19689 中贡献。)

SSLContext 方法 load_verify_locations() 接受新增的可选参数 cadata,它可被来分别通过字符串或字节串来直接提供 PEM 或 DER 编码的证书。 (由 Christian Heimes 在 bpo-18138 中贡献。)

新增的函数 get_default_verify_paths() 可返回一个由路径和环境变量组成的具名元组, 供 set_default_verify_paths() 方法用来设置 OpenSSL 的默认 cafile 和``capath``。 这有助于对默认的验证问题进行调试。 (由 Christian Heimes 在 bpo-18143 中贡献。)

SSLContext 增加了一个新方法 cert_store_stats(),用来报告已加载的 X.509 证书, X.509 CA 证书数量和证书吊销列表 (crls),以及 get_ca_certs() 方法用来返回已加载的 CA 证书列表。 (由 Christian Heimes 在 bpo-18147 中贡献。)

如果 OpenSSL 0.9.8 或更高版本可用,SSLContext 将具有一个新增属性 verify_flags 可被用于通过设置新增常量 VERIFY_DEFAULT, VERIFY_CRL_CHECK_LEAF, VERIFY_CRL_CHECK_CHAINVERIFY_X509_STRICT 的组合来控制证书验证过程。 在默认情况下 OpenSSL 不会执行任何 CRL 验证。 (由 Christien Heimes 在 bpo-8813 中贡献。)

新增的 SSLContext 方法 load_default_certs() 可从默认位置加载一组默认的“证书颁发机构”(CA)证书,此位置随平台而异。 它可被用于加载 TLS Web 服务器验证证书 (purpose=SERVER_AUTH ) 供客户端用来验证服务器,或加载证书供服务器用来验证客户端证书 (purpose=CLIENT_AUTH )。 (由 Christian Heimes 在 bpo-19292 中贡献。)

新增的两个 Windows 专属函数 enum_certificates()enum_crls() 提供了从 Windows 证书存储库提取证书、证书信息和 CRL 的功能。 (由 Christian Heimes 在 bpo-17134 中贡献。)

使用新增的 ssl.SSLContext.set_servername_callback() 方法来支持服务器端 SNI (Server Name Indication)。 (由 Daniel Black 在 bpo-8109 中贡献。)

SSLSocket.getpeercert() 返回的字典包含额外的 X509v3 扩展条目: crlDistributionPoints, calIssuersOCSP URI。 (由 Christian Heimes 在 bpo-18379 中贡献。)

stat

现在 stat 模块以 _stat 中的 C 实现作为后端。 C 实现是必需的因为大多数值都未被标准化并且依赖于平台。 (由 Christian Heimes 在 bpo-11016 中贡献。)

该模块支持新的 ST_MODE 旗标, S_IFDOOR, S_IFPORTS_IFWHT。 (由 Christian Hiemes 在 bpo-11016 中贡献。)

struct

新增函数 iter_unpack 和在已编译格式上的新增方法 struct.Struct.iter_unpack() 提供了对包含给定格式数据的重复实例的缓冲区的流式解包功能。 (由 Antoine Pitrou 在 bpo-17804 中贡献。)

subprocess

现在 check_output() 接受一个 input 参数用于为所运行的命令提供 stdin 的内容。 (由 Zack Weinberg 在 bpo-16624 中贡献。)

现在 getstatus()getstatusoutput() 已适用于 Windows。 这一修改是在 3.3.4 中意外实施的。 (由 Tim Golden 在 bpo-10197 中贡献。)

sunau

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-18901.)

sunau.open() now supports the context management protocol: when used in a with block, the close method of the returned object will be called automatically at the end of the block. (Contributed by Serhiy Storchaka in bpo-18878.)

现在 AU_write.setsampwidth() 已支持 24 位采样,因此增加了使用该模块写入 24 位采样的支持。 (由 Serhiy Storchaka 在 bpo-19261 中贡献。)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311.)

sys

新增函数 sys.getallocatedblocks() 可返回当前由解释器所分配的内存块数量。 (在使用默认 --with-pymalloc 设置的 CPython 中,这将是通过 PyObject_Malloc() API 执行的分配。) 这在追踪内存泄漏时会很有用处,特别是对于通过测试套件自动追踪的场景。 (由 Antoine Pitrou 在 bpo-13390 中贡献。)

当 Python 解释器以 交互模式 启动时,它会检查 sys 模块中的 __interactivehook__ 属性。 如果该属性存在,它的值将在交互模式启动之前不附带参数地被调用。 这个检查是在读取 PYTHONSTARTUP 文件之后进行的,因此可以在那里设置它。 site 模块会在平台支持 readline 的情况下 把它设置为 一个启用制表符补全和历史记录保存(在 ~/.python-history 中)的函数。 如果你不想要这个(新增的)行为,可以通过从 sys 中删除这个属性(或将其设为其他可调用对象)在 PYTHONSTARTUP, sitecustomizeusercustomize 中覆盖它。 (由 Éric Araujo 和 Antoine Pitrou 在 bpo-5845 中贡献。)

tarfile

现在 tarfile 模块当直接作为脚本或通过 -m 调用时将支持简单的 命令行接口。 这可被用来创建和提取 tar 归档文件。 (由 Berker Peksag 在 bpo-13477 中贡献。)

textwrap

TextWrapper 类新增了两个属性/构造器参数: max_lines,用来限制输出的行数,以及 placeholder,它是一个当输出由于 max_lines 限制被截断时将出现在输出末尾处的字符串。 一个在此功能之上新增的便捷函数 shorten() 可将输入中的所有空格压缩为单个空格并产生一个宽度为 width 并以 placeholder (默认为 [...]) 结束的单独行。 (由 Antoine Pitrou 和 Serhiy Storchaka 在 bpo-18585bpo-18725 中贡献。)

threading

代表可通过新增的 main_thread() 函数来获取的主线程的 Thread 对象。 在通常条件下这将是启动 Python 解释器所在的线程。 (由 Andrew Svetlov 在 bpo-18882 中贡献。)

回溯

新增的 traceback.clear_frames() 函数可接受一个回溯对象清除它所引用的所有帧中的局部变量,以减少内存消耗量。 (由 Andrew Kuchling 在 bpo-1565525 中贡献。)

types

A new DynamicClassAttribute() descriptor provides a way to define an attribute that acts normally when looked up through an instance object, but which is routed to the class __getattr__ when looked up through the class. This allows one to have properties active on a class, and have virtual attributes on the class with the same name (see Enum for an example). (Contributed by Ethan Furman in bpo-19030.)

urllib

现在 urllib.request 支持 data: 使用 DataHandler 类的 URL。 (由 Mathias Panzenböck 在 bpo-16423 中贡献。)

The http method that will be used by a Request class can now be specified by setting a method class attribute on the subclass. (Contributed by Jason R Coombs in bpo-18978.)

Request objects are now reusable: if the full_url or data attributes are modified, all relevant internal properties are updated. This means, for example, that it is now possible to use the same Request object in more than one OpenerDirector.open() call with different data arguments, or to modify a Request's url rather than recomputing it from scratch. There is also a new remove_header() method that can be used to remove headers from a Request. (Contributed by Alexey Kachayev in bpo-16464, Daniel Wozniak in bpo-17485, and Damien Brecht and Senthil Kumaran in bpo-17272.)

HTTPError objects now have a headers attribute that provides access to the HTTP response headers associated with the error. (Contributed by Berker Peksag in bpo-15701.)

unittest

The TestCase class has a new method, subTest(), that produces a context manager whose with block becomes a "sub-test". This context manager allows a test method to dynamically generate subtests by, say, calling the subTest context manager inside a loop. A single test method can thereby produce an indefinite number of separately identified and separately counted tests, all of which will run even if one or more of them fail. For example:

class NumbersTest(unittest.TestCase):
    def test_even(self):
        for i in range(6):
            with self.subTest(i=i):
                self.assertEqual(i % 2, 0)

will result in six subtests, each identified in the unittest verbose output with a label consisting of the variable name i and a particular value for that variable (i=0, i=1, etc). See 使用子测试区分测试迭代 for the full version of this example. (Contributed by Antoine Pitrou in bpo-16997.)

unittest.main() now accepts an iterable of test names for defaultTest, where previously it only accepted a single test name as a string. (Contributed by Jyrki Pulliainen in bpo-15132.)

If SkipTest is raised during test discovery (that is, at the module level in the test file), it is now reported as a skip instead of an error. (Contributed by Zach Ware in bpo-16935.)

discover() now sorts the discovered files to provide consistent test ordering. (Contributed by Martin Melin and Jeff Ramnani in bpo-16709.)

TestSuite now drops references to tests as soon as the test has been run, if the test is successful. On Python interpreters that do garbage collection, this allows the tests to be garbage collected if nothing else is holding a reference to the test. It is possible to override this behavior by creating a TestSuite subclass that defines a custom _removeTestAtIndex method. (Contributed by Tom Wardill, Matt McClure, and Andrew Svetlov in bpo-11798.)

A new test assertion context-manager, assertLogs(), will ensure that a given block of code emits a log message using the logging module. By default the message can come from any logger and have a priority of INFO or higher, but both the logger name and an alternative minimum logging level may be specified. The object returned by the context manager can be queried for the LogRecords and/or formatted messages that were logged. (Contributed by Antoine Pitrou in bpo-18937.)

Test discovery now works with namespace packages (Contributed by Claudiu Popa in bpo-17457.)

unittest.mock objects now inspect their specification signatures when matching calls, which means an argument can now be matched by either position or name, instead of only by position. (Contributed by Antoine Pitrou in bpo-17015.)

mock_open() objects now have readline and readlines methods. (Contributed by Toshio Kuratomi in bpo-17467.)

venv

venv now includes activation scripts for the csh and fish shells. (Contributed by Andrew Svetlov in bpo-15417.)

EnvBuilder and the create() convenience function take a new keyword argument with_pip, which defaults to False, that controls whether or not EnvBuilder ensures that pip is installed in the virtual environment. (Contributed by Nick Coghlan in bpo-19552 as part of the PEP 453 implementation.)

wave

The getparams() method now returns a namedtuple rather than a plain tuple. (Contributed by Claudiu Popa in bpo-17487.)

wave.open() now supports the context management protocol. (Contributed by Claudiu Popa in bpo-17616.)

wave can now write output to unseekable files. (Contributed by David Jones, Guilherme Polo, and Serhiy Storchaka in bpo-5202.)

The writeframesraw() and writeframes() methods now accept any bytes-like object. (Contributed by Serhiy Storchaka in bpo-8311.)

weakref

New WeakMethod class simulates weak references to bound methods. (Contributed by Antoine Pitrou in bpo-14631.)

New finalize class makes it possible to register a callback to be invoked when an object is garbage collected, without needing to carefully manage the lifecycle of the weak reference itself. (Contributed by Richard Oudkerk in bpo-15528.)

The callback, if any, associated with a ref is now exposed via the __callback__ attribute. (Contributed by Mark Dickinson in bpo-17643.)

xml.etree

A new parser, XMLPullParser, allows a non-blocking applications to parse XML documents. An example can be seen at 用于非阻塞解析的拉取 API. (Contributed by Antoine Pitrou in bpo-17741.)

The xml.etree.ElementTree tostring() and tostringlist() functions, and the ElementTree write() method, now have a short_empty_elements keyword-only parameter providing control over whether elements with no content are written in abbreviated (<tag />) or expanded (<tag></tag>) form. (Contributed by Ariel Poliak and Serhiy Storchaka in bpo-14377.)

zipfile

The writepy() method of the PyZipFile class has a new filterfunc option that can be used to control which directories and files are added to the archive. For example, this could be used to exclude test files from the archive. (Contributed by Christian Tismer in bpo-19274.)

The allowZip64 parameter to ZipFile and PyZipfile is now True by default. (Contributed by William Mallard in bpo-17201.)

CPython 实现的变化

PEP 445: 自定义 CPython 内存分配器

PEP 445 添加了新的 C 层级接口用来在 CPython 解释器中对内存分配进行自定义。

参见

PEP 445 -- 新增用于自定义 Python 内存分配器的 API

PEP 由 Victor Stinner 撰写并实现。

PEP 442: 安全的对象最终化

PEP 442 removes the current limitations and quirks of object finalization in CPython. With it, objects with __del__() methods, as well as generators with finally clauses, can be finalized when they are part of a reference cycle.

As part of this change, module globals are no longer forcibly set to None during interpreter shutdown in most cases, instead relying on the normal operation of the cyclic garbage collector. This avoids a whole class of interpreter-shutdown-time errors, usually involving __del__ methods, that have plagued Python since the cyclic GC was first introduced.

参见

PEP 442 -- Safe object finalization

PEP 由 Antoine Pitrou 撰写并实现

PEP 456: Secure and Interchangeable Hash Algorithm

PEP 456 follows up on earlier security fix work done on Python's hash algorithm to address certain DOS attacks to which public facing APIs backed by dictionary lookups may be subject. (See bpo-14621 for the start of the current round of improvements.) The PEP unifies CPython's hash code to make it easier for a packager to substitute a different hash algorithm, and switches Python's default implementation to a SipHash implementation on platforms that have a 64 bit data type. Any performance differences in comparison with the older FNV algorithm are trivial.

The PEP adds additional fields to the sys.hash_info named tuple to describe the hash algorithm in use by the currently executing binary. Otherwise, the PEP does not alter any existing CPython APIs.

PEP 436: Argument Clinic

"Argument Clinic" (PEP 436) is now part of the CPython build process and can be used to simplify the process of defining and maintaining accurate signatures for builtins and standard library extension modules implemented in C.

Some standard library extension modules have been converted to use Argument Clinic in Python 3.4, and pydoc and inspect have been updated accordingly.

It is expected that signature metadata for programmatic introspection will be added to additional callables implemented in C as part of Python 3.4 maintenance releases.

备注

The Argument Clinic PEP is not fully up to date with the state of the implementation. This has been deemed acceptable by the release manager and core development team in this case, as Argument Clinic will not be made available as a public API for third party use in Python 3.4.

参见

PEP 436 -- The Argument Clinic DSL

PEP 由 Larry Hastings 撰写并实现

其他的构建和 C API 的改变

  • The new PyType_GetSlot() function has been added to the stable ABI, allowing retrieval of function pointers from named type slots when using the limited API. (Contributed by Martin von Löwis in bpo-17162.)

  • The new Py_SetStandardStreamEncoding() pre-initialization API allows applications embedding the CPython interpreter to reliably force a particular encoding and error handler for the standard streams. (Contributed by Bastien Montagne and Nick Coghlan in bpo-16129.)

  • Most Python C APIs that don't mutate string arguments are now correctly marked as accepting const char * rather than char *. (Contributed by Serhiy Storchaka in bpo-1772673.)

  • A new shell version of python-config can be used even when a python interpreter is not available (for example, in cross compilation scenarios).

  • PyUnicode_FromFormat() now supports width and precision specifications for %s, %A, %U, %V, %S, and %R. (Contributed by Ysj Ray and Victor Stinner in bpo-7330.)

  • New function PyStructSequence_InitType2() supplements the existing PyStructSequence_InitType() function. The difference is that it returns 0 on success and -1 on failure.

  • The CPython source can now be compiled using the address sanity checking features of recent versions of GCC and clang: the false alarms in the small object allocator have been silenced. (Contributed by Dhiru Kholia in bpo-18596.)

  • The Windows build now uses Address Space Layout Randomization and Data Execution Prevention. (Contributed by Christian Heimes in bpo-16632.)

  • New function PyObject_LengthHint() is the C API equivalent of operator.length_hint(). (Contributed by Armin Ronacher in bpo-16148.)

其他改进

  • The python command has a new option, -I, which causes it to run in "isolated mode", which means that sys.path contains neither the script's directory nor the user's site-packages directory, and all PYTHON* environment variables are ignored (it implies both -s and -E). Other restrictions may also be applied in the future, with the goal being to isolate the execution of a script from the user's environment. This is appropriate, for example, when Python is used to run a system script. On most POSIX systems it can and should be used in the #! line of system scripts. (Contributed by Christian Heimes in bpo-16499.)

  • Tab-completion is now enabled by default in the interactive interpreter on systems that support readline. History is also enabled by default, and is written to (and read from) the file ~/.python-history. (Contributed by Antoine Pitrou and Éric Araujo in bpo-5845.)

  • Invoking the Python interpreter with --version now outputs the version to standard output instead of standard error (bpo-18338). Similar changes were made to argparse (bpo-18920) and other modules that have script-like invocation capabilities (bpo-18922).

  • The CPython Windows installer now adds .py to the PATHEXT variable when extensions are registered, allowing users to run a python script at the windows command prompt by just typing its name without the .py extension. (Contributed by Paul Moore in bpo-18569.)

  • A new make target coverage-report will build python, run the test suite, and generate an HTML coverage report for the C codebase using gcov and lcov.

  • The -R option to the python regression test suite now also checks for memory allocation leaks, using sys.getallocatedblocks(). (Contributed by Antoine Pitrou in bpo-13390.)

  • python -m now works with namespace packages.

  • The stat module is now implemented in C, which means it gets the values for its constants from the C header files, instead of having the values hard-coded in the python module as was previously the case.

  • 现在将能够正确地从单个 OS 模块加载多个 (.so, .dll) python 模块(在之前版本中则会静默地返回文件中的第一个 python 模块)。 (由 Václav Šmilauer 在 bpo-16421 中贡献。)

  • 增加了新的操作码 LOAD_CLASSDEREF,用于修复一个在类体中加载自由变量的程序错误,它可能因 __prepare__ 的特定用法而触发。 (由 Benjamin Peterson 在 bpo-17853 中贡献。)

  • 多个有关 MemoryError 的崩溃问题被 Victor Stinner 使用他基于 PEP 445pyfailmalloc 工具加以确定并修复 (bpo-18408, bpo-18520)。

  • 现在 pyvenv 命令接受一个 --copies 选项以使用拷贝而不是符号链接,即使在默认使用符号链接的系统上也是如此。 (由 Vinay Sajip 在 bpo-18807 中贡献。)

  • pyvenv 命令也接受一个 --without-pip 选项用来抑制在其他情况下将自动将 pip 初始设置到虚拟环境中。 (作为 PEP 453 实现的一部分由 Nick Coghlan 在 bpo-19552 中贡献。)

  • 现在编码格式名称在 PYTHONIOENCODING 环境变量的设置值中将为可选项。 这使得只设置错误处理器而不改变默认编码格式成为可能。 (由 Serhiy Storchaka 在 bpo-18818 中贡献。)

  • 现在 bz2, lzma, and gzip 模块的 open 函数已支持 x (独占式创建) 模式。 (由 Tim Heaney 和 Vajrasky Kok 在 bpo-19201, bpo-19222bpo-19223 中贡献。)

显著的优化

  • 现在 UTF-32 解码器获得了 3x 至 4x 的提速。 (由 Serhiy Storchaka 在 bpo-14625 中贡献。)

  • The cost of hash collisions for sets is now reduced. Each hash table probe now checks a series of consecutive, adjacent key/hash pairs before continuing to make random probes through the hash table. This exploits cache locality to make collision resolution less expensive. The collision resolution scheme can be described as a hybrid of linear probing and open addressing. The number of additional linear probes defaults to nine. This can be changed at compile-time by defining LINEAR_PROBES to be any value. Set LINEAR_PROBES=0 to turn-off linear probing entirely. (Contributed by Raymond Hettinger in bpo-18771.)

  • The interpreter starts about 30% faster. A couple of measures lead to the speedup. The interpreter loads fewer modules on startup, e.g. the re, collections and locale modules and their dependencies are no longer imported by default. The marshal module has been improved to load compiled Python code faster. (Contributed by Antoine Pitrou, Christian Heimes and Victor Stinner in bpo-19219, bpo-19218, bpo-19209, bpo-19205 and bpo-9548.)

  • bz2.BZ2File is now as fast or faster than the Python2 version for most cases. lzma.LZMAFile has also been optimized. (Contributed by Serhiy Storchaka and Nadeem Vawda in bpo-16034.)

  • random.getrandbits() is 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in bpo-16674.)

  • By taking advantage of the new storage format for strings, pickling of strings is now significantly faster. (Contributed by Victor Stinner and Antoine Pitrou in bpo-15596.)

  • A performance issue in io.FileIO.readall() has been solved. This particularly affects Windows, and significantly speeds up the case of piping significant amounts of data through subprocess. (Contributed by Richard Oudkerk in bpo-15758.)

  • html.escape() is now 10x faster. (Contributed by Matt Bryant in bpo-18020.)

  • On Windows, the native VirtualAlloc is now used instead of the CRT malloc in obmalloc. Artificial benchmarks show about a 3% memory savings.

  • os.urandom() now uses a lazily opened persistent file descriptor so as to avoid using many file descriptors when run in parallel from multiple threads. (Contributed by Antoine Pitrou in bpo-18756.)

弃用

This section covers various APIs and other features that have been deprecated in Python 3.4, and will be removed in Python 3.5 or later. In most (but not all) cases, using the deprecated APIs will produce a DeprecationWarning when the interpreter is run with deprecation warnings enabled (for example, by using -Wd).

Python API 中的弃用

  • As mentioned in PEP 451: 针对导入系统的 ModuleSpec 类型, a number of importlib methods and functions are deprecated: importlib.find_loader() is replaced by importlib.util.find_spec(); importlib.machinery.PathFinder.find_module() is replaced by importlib.machinery.PathFinder.find_spec(); importlib.abc.MetaPathFinder.find_module() is replaced by importlib.abc.MetaPathFinder.find_spec(); importlib.abc.PathEntryFinder.find_loader() and find_module() are replaced by importlib.abc.PathEntryFinder.find_spec(); all of the xxxLoader ABC load_module methods (importlib.abc.Loader.load_module(), importlib.abc.InspectLoader.load_module(), importlib.abc.FileLoader.load_module(), importlib.abc.SourceLoader.load_module()) should no longer be implemented, instead loaders should implement an exec_module method (importlib.abc.Loader.exec_module(), importlib.abc.InspectLoader.exec_module() importlib.abc.SourceLoader.exec_module()) and let the import system take care of the rest; and importlib.abc.Loader.module_repr(), importlib.util.module_for_loader(), importlib.util.set_loader(), and importlib.util.set_package() are no longer needed because their functions are now handled automatically by the import system.

  • imp 模块已被弃用。 为保持与 Python 2/3 基础代码的兼容性,目前还没有移除该模块的计划。

  • formatter 模块已被弃用并计划在 Python 3.6 中移除。

  • MD5 作为 hmac.new() 函数的默认 digestmod 的设置已被弃用。 Python 3.6 将要求以一个显式的摘要名称或构造器作为 digestmod 参数。

  • 很长一段时间以来 ftplib 模块中的内部 Netrc 类在其文档字符串中被声明为已弃用。 现在它将发出 DeprecationWarning 并将在 Python 3.5 中完全移除。

  • 传给 subprocess.Popen.wait() 的未写入文档的 endtime 参数不应被公开也不应被使用;它已被弃用并很可能在 Python 3.5 中移除。

  • The strict argument of HTMLParser is deprecated.

  • The plistlib readPlist(), writePlist(), readPlistFromBytes(), and writePlistToBytes() functions are deprecated in favor of the corresponding new functions load(), dump(), loads(), and dumps(). Data() is deprecated in favor of just using the bytes constructor.

  • The sysconfig key SO is deprecated, it has been replaced by EXT_SUFFIX.

  • The U mode accepted by various open functions is deprecated. In Python3 it does not do anything useful, and should be replaced by appropriate uses of io.TextIOWrapper (if needed) and its newline argument.

  • The parser argument of xml.etree.ElementTree.iterparse() has been deprecated, as has the html argument of XMLParser(). To prepare for the removal of the latter, all arguments to XMLParser should be passed by keyword.

弃用的特性

  • Running IDLE with the -n flag (no subprocess) is deprecated. However, the feature will not be removed until bpo-18823 is resolved.

  • The site module adding a "site-python" directory to sys.path, if it exists, is deprecated (bpo-19375).

移除

不再支持的操作系统

从源代码和构建工具中删除了对以下操作系统的支持:

  • OS/2 (bpo-16135).

  • Windows 2000(变更集e52df05b496a)。

  • Windows系统中 COMSPEC 指向 command.com 的版本( bpo-14470 )。

  • VMS (bpo-16136).

API 与特性的移除

以下过时并在之前版本中弃用的 API 和特性现已被移除:

  • The unmaintained Misc/TextMate and Misc/vim directories have been removed (see the devguide for suggestions on what to use instead).

  • The SO makefile macro is removed (it was replaced by the SHLIB_SUFFIX and EXT_SUFFIX macros) (bpo-16754).

  • The PyThreadState.tick_counter field has been removed; its value has been meaningless since Python 3.2, when the "new GIL" was introduced (bpo-19199).

  • PyLoader and PyPycLoader have been removed from importlib. (Contributed by Taras Lyapun in bpo-15641.)

  • The strict argument to HTTPConnection and HTTPSConnection has been removed. HTTP 0.9-style "Simple Responses" are no longer supported.

  • The deprecated urllib.request.Request getter and setter methods add_data, has_data, get_data, get_type, get_host, get_selector, set_proxy, get_origin_req_host, and is_unverifiable have been removed (use direct attribute access instead).

  • Support for loading the deprecated TYPE_INT64 has been removed from marshal. (Contributed by Dan Riti in bpo-15480.)

  • inspect.Signature: positional-only parameters are now required to have a valid name.

  • object.__format__() no longer accepts non-empty format strings, it now raises a TypeError instead. Using a non-empty string has been deprecated since Python 3.2. This change has been made to prevent a situation where previously working (but incorrect) code would start failing if an object gained a __format__ method, which means that your code may now raise a TypeError if you are using an 's' format code with objects that do not have a __format__ method that handles it. See bpo-7994 for background.

  • difflib.SequenceMatcher.isbjunk()difflib.SequenceMatcher.isbpopular() 已在 3.2 中被弃用,现在已被移除:请使用 x in sm.bjunkx in sm.bpopular,其中 sm 是一个 SequenceMatcher 对象 (bpo-13248)。

代码清理

  • 未被使用并且未写入文档的内部 Scanner 类已从 pydoc 模块中移除。

  • 私有并且实际未使用的 _gestalt 模块已被移除,同时移除了私有的 platform 函数 _mac_ver_lookup, _mac_ver_gstalt_bcd2str,它们仅会在严重过时的 OSX 系统上被调用 (参见 bpo-18393)。

  • 曾经包括于 tarfile 模块命名空间的某些 stat 常量的硬编码副本已被移除。

移植到 Python 3.4

本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.

 'python' 命令行为的变化

  • In a posix shell, setting the PATH environment variable to an empty value is equivalent to not setting it at all. However, setting PYTHONPATH to an empty value was not equivalent to not setting it at all: setting PYTHONPATH to an empty value was equivalent to setting it to ., which leads to confusion when reasoning by analogy to how PATH works. The behavior now conforms to the posix convention for PATH.

  • The [X refs, Y blocks] output of a debug (--with-pydebug) build of the CPython interpreter is now off by default. It can be re-enabled using the -X showrefcount option. (Contributed by Ezio Melotti in bpo-17323.)

  • The python command and most stdlib scripts (as well as argparse) now output --version information to stdout instead of stderr (for issue list see 其他改进 above).

Python API 的变化

  • The ABCs defined in importlib.abc now either raise the appropriate exception or return a default value instead of raising NotImplementedError blindly. This will only affect code calling super() and falling through all the way to the ABCs. For compatibility, catch both NotImplementedError or the appropriate exception as needed.

  • The module type now initializes the __package__ and __loader__ attributes to None by default. To determine if these attributes were set in a backwards-compatible fashion, use e.g. getattr(module, '__loader__', None) is not None. (bpo-17115.)

  • importlib.util.module_for_loader() now sets __loader__ and __package__ unconditionally to properly support reloading. If this is not desired then you will need to set these attributes manually. You can use importlib.util.module_to_load() for module management.

  • Import now resets relevant attributes (e.g. __name__, __loader__, __package__, __file__, __cached__) unconditionally when reloading. Note that this restores a pre-3.3 behavior in that it means a module is re-found when re-loaded (bpo-19413).

  • Frozen packages no longer set __path__ to a list containing the package name, they now set it to an empty list. The previous behavior could cause the import system to do the wrong thing on submodule imports if there was also a directory with the same name as the frozen package. The correct way to determine if a module is a package or not is to use hasattr(module, '__path__') (bpo-18065).

  • Frozen modules no longer define a __file__ attribute. It's semantically incorrect for frozen modules to set the attribute as they are not loaded from any explicit location. If you must know that a module comes from frozen code then you can see if the module's __spec__.location is set to 'frozen', check if the loader is a subclass of importlib.machinery.FrozenImporter, or if Python 2 compatibility is necessary you can use imp.is_frozen().

  • py_compile.compile() now raises FileExistsError if the file path it would write to is a symlink or a non-regular file. This is to act as a warning that import will overwrite those files with a regular file regardless of what type of file path they were originally.

  • importlib.abc.SourceLoader.get_source() no longer raises ImportError when the source code being loaded triggers a SyntaxError or UnicodeDecodeError. As ImportError is meant to be raised only when source code cannot be found but it should, it was felt to be over-reaching/overloading of that meaning when the source code is found but improperly structured. If you were catching ImportError before and wish to continue to ignore syntax or decoding issues, catch all three exceptions now.

  • functools.update_wrapper() and functools.wraps() now correctly set the __wrapped__ attribute to the function being wrapped, even if that function also had its __wrapped__ attribute set. This means __wrapped__ attributes now correctly link a stack of decorated functions rather than every __wrapped__ attribute in the chain referring to the innermost function. Introspection libraries that assumed the previous behaviour was intentional can use inspect.unwrap() to access the first function in the chain that has no __wrapped__ attribute.

  • inspect.getfullargspec() has been reimplemented on top of inspect.signature() and hence handles a much wider variety of callable objects than it did in the past. It is expected that additional builtin and extension module callables will gain signature metadata over the course of the Python 3.4 series. Code that assumes that inspect.getfullargspec() will fail on non-Python callables may need to be adjusted accordingly.

  • importlib.machinery.PathFinder now passes on the current working directory to objects in sys.path_hooks for the empty string. This results in sys.path_importer_cache never containing '', thus iterating through sys.path_importer_cache based on sys.path will not find all keys. A module's __file__ when imported in the current working directory will also now have an absolute path, including when using -m with the interpreter (except for __main__.__file__ when a script has been executed directly using a relative path) (Contributed by Brett Cannon in bpo-18416). is specified on the command-line) (bpo-18416).

  • The removal of the strict argument to HTTPConnection and HTTPSConnection changes the meaning of the remaining arguments if you are specifying them positionally rather than by keyword. If you've been paying attention to deprecation warnings your code should already be specifying any additional arguments via keywords.

  • Strings between from __future__ import ... statements now always raise a SyntaxError. Previously if there was no leading docstring, an interstitial string would sometimes be ignored. This brings CPython into compliance with the language spec; Jython and PyPy already were. (bpo-17434).

  • ssl.SSLSocket.getpeercert() and ssl.SSLSocket.do_handshake() now raise an OSError with ENOTCONN when the SSLSocket is not connected, instead of the previous behavior of raising an AttributeError. In addition, getpeercert() will raise a ValueError if the handshake has not yet been done.

  • base64.b32decode() now raises a binascii.Error when the input string contains non-b32-alphabet characters, instead of a TypeError. This particular TypeError was missed when the other TypeErrors were converted. (Contributed by Serhiy Storchaka in bpo-18011.) Note: this change was also inadvertently applied in Python 3.3.3.

  • The file attribute is now automatically closed when the creating cgi.FieldStorage instance is garbage collected. If you were pulling the file object out separately from the cgi.FieldStorage instance and not keeping the instance alive, then you should either store the entire cgi.FieldStorage instance or read the contents of the file before the cgi.FieldStorage instance is garbage collected.

  • Calling read or write on a closed SSL socket now raises an informative ValueError rather than the previous more mysterious AttributeError (bpo-9177).

  • slice.indices() no longer produces an OverflowError for huge values. As a consequence of this fix, slice.indices() now raises a ValueError if given a negative length; previously it returned nonsense values (bpo-14794).

  • The complex constructor, unlike the cmath functions, was incorrectly accepting float values if an object's __complex__ special method returned one. This now raises a TypeError. (bpo-16290.)

  • The int constructor in 3.2 and 3.3 erroneously accepts float values for the base parameter. It is unlikely anyone was doing this, but if so, it will now raise a TypeError (bpo-16772).

  • Defaults for keyword-only arguments are now evaluated after defaults for regular keyword arguments, instead of before. Hopefully no one wrote any code that depends on the previous buggy behavior (bpo-16967).

  • Stale thread states are now cleared after fork(). This may cause some system resources to be released that previously were incorrectly kept perpetually alive (for example, database connections kept in thread-local storage). (bpo-17094.)

  • Parameter names in __annotations__ dicts are now mangled properly, similarly to __kwdefaults__. (Contributed by Yury Selivanov in bpo-20625.)

  • hashlib.hash.name now always returns the identifier in lower case. Previously some builtin hashes had uppercase names, but now that it is a formal public interface the naming has been made consistent (bpo-18532).

  • Because unittest.TestSuite now drops references to tests after they are run, test harnesses that re-use a TestSuite to re-run a set of tests may fail. Test suites should not be re-used in this fashion since it means state is retained between test runs, breaking the test isolation that unittest is designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating a TestSuite subclass that defines a _removeTestAtIndex method that does nothing (see TestSuite.__iter__()) (bpo-11798).

  • unittest now uses argparse for command line parsing. There are certain invalid command forms that used to work that are no longer allowed; in theory this should not cause backward compatibility issues since the disallowed command forms didn't make any sense and are unlikely to be in use.

  • The re.split(), re.findall(), and re.sub() functions, and the group() and groups() methods of match objects now always return a bytes object when the string to be matched is a bytes-like object. Previously the return type matched the input type, so if your code was depending on the return value being, say, a bytearray, you will need to change your code.

  • audioop functions now raise an error immediately if passed string input, instead of failing randomly later on (bpo-16685).

  • The new convert_charrefs argument to HTMLParser currently defaults to False for backward compatibility, but will eventually be changed to default to True. It is recommended that you add this keyword, with the appropriate value, to any HTMLParser calls in your code (bpo-13633).

  • Since the digestmod argument to the hmac.new() function will in the future have no default, all calls to hmac.new() should be changed to explicitly specify a digestmod (bpo-17276).

  • Calling sysconfig.get_config_var() with the SO key, or looking SO up in the results of a call to sysconfig.get_config_vars() is deprecated. This key should be replaced by EXT_SUFFIX or SHLIB_SUFFIX, depending on the context (bpo-19555).

  • Any calls to open functions that specify U should be modified. U is ineffective in Python3 and will eventually raise an error if used. Depending on the function, the equivalent of its old Python2 behavior can be achieved using either a newline argument, or if necessary by wrapping the stream in TextIOWrapper to use its newline argument (bpo-15204).

  • If you use pyvenv in a script and desire that pip not be installed, you must add --without-pip to your command invocation.

  • The default behavior of json.dump() and json.dumps() when an indent is specified has changed: it no longer produces trailing spaces after the item separating commas at the ends of lines. This will matter only if you have tests that are doing white-space-sensitive comparisons of such output (bpo-16333).

  • 现在 doctest 会在扩展模块的 __doc__ 字符串中寻找 doctest,因此如果你的 doctest 测试发现包括具有类似 doctest 内容的扩展模块那么你可能会遇到在你之前运行测试时从未遇到过的测试失败 (bpo-3158)。

  • 作为 Python 启动过程改进的一部分 collections.abc 模块进行了小幅度的重构。 作为此项重构的结果,导入 collections 将不再自动导入 collections.abc。 如果你的程序依赖于这个(未写入文档的)隐式导入,你将需要添加显式的 import collections.abc (bpo-20784)。

C API 的变化

  • PyEval_EvalFrameEx(), PyObject_Repr(), and PyObject_Str(), along with some other internal C APIs, now include a debugging assertion that ensures they are not used in situations where they may silently discard a currently active exception. In cases where discarding the active exception is expected and desired (for example, because it has already been saved locally with PyErr_Fetch() or is being deliberately replaced with a different exception), an explicit PyErr_Clear() call will be needed to avoid triggering the assertion when invoking these operations (directly or indirectly) and running against a version of Python that is compiled with assertions enabled.

  • 现在 PyErr_SetImportError() 在其 msg 参数未被设置时会设置 TypeError。 在之前版本中仅会返回 NULL 而不设置异常。

  • 现在 PyOS_ReadlineFunctionPointer 回调的结果必须是一个由 PyMem_RawMalloc()PyMem_RawRealloc() 分配的字符串,或者如果发生错误则为 NULL,而不是由 PyMem_Malloc()PyMem_Realloc() 分配的字符串 (bpo-16742)

  • 现在 PyThread_set_key_value() 总是会设置值。 在 Python 3.3 中,如果键已存在(如果当前值为非 NULL 指针)该函数将不执行任何操作。

  • PyFrameObject 结构体的 f_tstate (线程状态) 字段已被移除以修复一个程序错误;相关理由参见 bpo-14432

3.4.3 的变化

PEP 476: 默认为 stdlib http 客户端启用证书验证

http.client 及其他依赖它的模块,比如 urllib.requestxmlrpc.client,现在将验证服务器是否提供了由平台信任的仓库中的 CA 签名的证书并且其主机名与默认被请求的主机名相匹配,这将显著提升许多应用程序的安全性。

对于需要之前版本的旧有行为的应用程序,可以传入一个替代的上下文:

import urllib.request
import ssl

# This disables all verification
context = ssl._create_unverified_context()

# This allows using a specific certificate for the host, which doesn't need
# to be in the trust store
context = ssl.create_default_context(cafile="/path/to/file.crt")

urllib.request.urlopen("https://invalid-cert", context=context)