poplib
在 poplib
中新增了两个方法: capa()
,它将返回 POP 服务器公开的功能列表,以及 stls()
,它将在 POP 支持的情况下将明文 POP3 会话切换为加密 POP3 会话。 (由 Lorenzo Catucci 在 bpo-4473 [https://bugs.python.org/issue?@action=redirect&bpo=4473] 中贡献。)
pprint
pprint
模块的 PrettyPrinter
类以及 pformat()
和 pprint()
函数新增了一个选项 compact,它可控制输出所使用的格式。 目前将 compact 设为 True
表示打印序列时将在每个(缩进的)行中放入 width 所允许的尽可能多的元素。 (由 Serhiy Storchaka 在 bpo-19132 [https://bugs.python.org/issue?@action=redirect&bpo=19132] 中贡献。)
长字符串现在将使用 Python 的常规续行语法进行包装。 (由 Antoine Pitrou 在 bpo-17150 [https://bugs.python.org/issue?@action=redirect&bpo=17150] 中贡献。)
pty
现在 pty.spawn()
将返回来自子进程上 os.waitpid()
的状态值,而不是 None
。 (由 Gregory P. Smith 贡献。)
pydoc
现在 pydoc
模块是直接基于 inspect.signature()
内省 API,这允许它提供更多可调用对象的签名信息。 这一改变也意味着现在当显示帮助信息时 __wrapped__
属性也会被纳入考虑。 (由 Larry Hastings 在 bpo-19674 [https://bugs.python.org/issue?@action=redirect&bpo=19674] 中贡献。)
pydoc
模块将不再显示已绑定方法的 self
形参。 现在,它总是会显示所提供可调用对象实际的当前签名。 (由 Larry Hastings 在 bpo-20710 [https://bugs.python.org/issue?@action=redirect&bpo=20710] 中贡献。)
除了 pydoc
已有的直接修改,它对自定义 __dir__
方法和各种描述器行为的处理也通过对下层 inspect
模块的修改获得了显著的改进。
由于 help()
内置函数是基于 pydoc
的,上述的变化也会影响 help()
的行为。
re
新增的 fullmatch()
函数和 regex.fullmatch()
方法可将模式锚定到要匹配的字符串的两端。 这提供了一种明确匹配目标的方式,从而避免了一类微妙的错误错误,即在代码更改或为现有正则表达式添加替代项时丢失 $
字符。 (由 Matthew Barnett 在 bpo-16203 [https://bugs.python.org/issue?@action=redirect&bpo=16203] 中贡献。)
正则表达式对象 的 repr 现在将包括模式和旗标;匹配对象 的 repr 现在将包括已匹配字符串的开头、末尾和组成。 (由 Hugo Lopes Tavares 和 Serhiy Storchaka 在 bpo-13592 [https://bugs.python.org/issue?@action=redirect&bpo=13592] 和 bpo-17087 [https://bugs.python.org/issue?@action=redirect&bpo=17087] 中贡献。)
resource
新增的 prlimit()
函数,在内核版本 2.6.36 以上的 Linux 平台及 glibc 版本 2.13 以上可用,提供了查询或设置执行调用的进程以外的进程的资源限制的功能。 (由 Christian Heimes 在 bpo-16595 [https://bugs.python.org/issue?@action=redirect&bpo=16595] 中贡献。)
在内核版本 2.6.36 以上的 Linux 上,新增了一些 Linux 专属的常量: RLIMIT_MSGQUEUE
, RLIMIT_NICE
, RLIMIT_RTPRIO
, RLIMIT_RTTIME
和 RLIMIT_SIGPENDING
。 (由 Christian Heimes 在 bpo-19324 [https://bugs.python.org/issue?@action=redirect&bpo=19324] 中贡献。)
在版本 9 以上的 FreeBSD 上,新增了一些 FreeBSD 专属的常量: RLIMIT_SBSIZE
, RLIMIT_SWAP
和 RLIMIT_NPTS
。 (由 Claudiu Popa 在 bpo-19343 [https://bugs.python.org/issue?@action=redirect&bpo=19343] 中贡献。)
select
现在 epoll
对象可支持上下文管理协议。 当在 with
语句中使用时,close()
方法将在代码块结束时被自动调用。 (由 Serhiy Storchaka 在 bpo-16488 [https://bugs.python.org/issue?@action=redirect&bpo=16488] 中贡献。)
现在 devpoll
对象具有 fileno()
和 close()
方法,以及新的属性 closed
。 (由 Victor Stinner 在 bpo-18794 [https://bugs.python.org/issue?@action=redirect&bpo=18794] 中贡献。)
shelve
现在 Shelf
实例可以在 with
语句中使用,并将在 with
代码块结束时自动关闭。 (由 Filip Gruszczyński 在 bpo-13896 [https://bugs.python.org/issue?@action=redirect&bpo=13896] 中贡献。)
shutil
现在当源和目标为相同文件时 copyfile()
会引发专门的 Error
子类 SameFileError
,这允许应用程序针对这个特定错误采取适当的动作。 (由 Atsuo Ishimoto 和 Hynek Schlawack 在 bpo-1492704 [https://bugs.python.org/issue?@action=redirect&bpo=1492704] 中贡献。)
smtpd
现在 SMTPServer
和 SMTPChannel
类接受一个 map 关键字参数,如果指定了该参数,它将被传给 asynchat.async_chat
作为其 map 参数。 这允许应用程序避免影响全局套接字映射表。 (由 Vinay Sajip 在 bpo-11959 [https://bugs.python.org/issue?@action=redirect&bpo=11959] 中贡献。)
smtplib
现在 SMTPException
是 OSError
的子类,它允许仅需关注是否有错误发生的代码在一个 try/except 语句中同时捕获套接字级错误和 SMTP 协议级错误。 (由 Ned Jackson Lovely 在 bpo-2118 [https://bugs.python.org/issue?@action=redirect&bpo=2118] 中贡献。)
socket
现在 socket 模块会在受支持的平台上支持 CAN_BCM
协议。 (由 Brian Thorne 在 bpo-15359 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=7171] 中贡献。)
sqlite3
connect()
函数新增布尔值形参 uri,它可被用来指明 database 形参是一个 uri
(参见 SQLite URI 文档 [https://www.sqlite.org/uri.html])。 (由 poq 在 bpo-13773 [https://bugs.python.org/issue?@action=redirect&bpo=13773] 中贡献。)
ssl
添加了 PROTOCOL_TLSv1_1
和 PROTOCOL_TLSv1_2
(TLSv1.1 和 TLSv1.2 支持);对这些协议的支持仅在 Python 使用 OpenSSL 1.0.1 或更高版本链接时可用。 (由 Michele Orrù 和 Antoine Pitrou 在 bpo-16692 [https://bugs.python.org/issue?@action=redirect&bpo=16692] 中贡献。)
新增的函数 create_default_context()
提供了获取 SSLContext
的标准方式,其设置旨在合理兼顾兼容性和安全性。 这些设置比 SSLContext
构造器所提供的默认设置更为严格,如果最佳实践的安全要求发生变化,将来可能会对其进行调整,而不预先提示弃用。 对于使用支持 SSL 的 stdlib 库来新推荐的最佳实践是使用 create_default_context()
来获取 SSLContext
对象,必要时对其进行修改,然后将其作为相应 stdlib API 的 contex 参数传入。 (由 Christian Heimes 在 bpo-19689 [https://bugs.python.org/issue?@action=redirect&bpo=19689] 中贡献。)
SSLContext
方法 load_verify_locations()
接受新增的可选参数 cadata,它可被来分别通过字符串或字节串来直接提供 PEM 或 DER 编码的证书。 (由 Christian Heimes 在 bpo-18138 [https://bugs.python.org/issue?@action=redirect&bpo=18138] 中贡献。)
新增的函数 get_default_verify_paths()
可返回一个由路径和环境变量组成的具名元组, 供 set_default_verify_paths()
方法用来设置 OpenSSL 的默认 cafile
和capath
。 这有助于对默认的验证问题进行调试。 (由 Christian Heimes 在 bpo-18143 [https://bugs.python.org/issue?@action=redirect&bpo=18143] 中贡献。)
SSLContext
增加了一个新方法 cert_store_stats()
,用来报告已加载的 X.509
证书, X.509 CA
证书数量和证书吊销列表 (crl
s),以及 get_ca_certs()
方法用来返回已加载的 CA
证书列表。 (由 Christian Heimes 在 bpo-18147 [https://bugs.python.org/issue?@action=redirect&bpo=18147] 中贡献。)
如果 OpenSSL 0.9.8 或更高版本可用,SSLContext
将具有一个新增属性 verify_flags
可被用于通过设置新增常量 VERIFY_DEFAULT
, VERIFY_CRL_CHECK_LEAF
, VERIFY_CRL_CHECK_CHAIN
或 VERIFY_X509_STRICT
的组合来控制证书验证过程。 在默认情况下 OpenSSL 不会执行任何 CRL 验证。 (由 Christien Heimes 在 bpo-8813 [https://bugs.python.org/issue?@action=redirect&bpo=8813] 中贡献。)
新增的 SSLContext
方法 load_default_certs()
可从默认位置加载一组默认的“证书颁发机构”(CA)证书,此位置随平台而异。 它可被用于加载 TLS Web 服务器验证证书 (purpose=
SERVER_AUTH
) 供客户端用来验证服务器,或加载证书供服务器用来验证客户端证书 (purpose=
CLIENT_AUTH
)。 (由 Christian Heimes 在 bpo-19292 [https://bugs.python.org/issue?@action=redirect&bpo=19292] 中贡献。)
新增的两个 Windows 专属函数 enum_certificates()
和 enum_crls()
提供了从 Windows 证书存储库提取证书、证书信息和 CRL 的功能。 (由 Christian Heimes 在 bpo-17134 [https://bugs.python.org/issue?@action=redirect&bpo=17134] 中贡献。)
使用新增的 ssl.SSLContext.set_servername_callback()
方法来支持服务器端 SNI (Server Name Indication)。 (由 Daniel Black 在 bpo-8109 [https://bugs.python.org/issue?@action=redirect&bpo=8109] 中贡献。)
由 SSLSocket.getpeercert()
返回的字典包含额外的 X509v3
扩展条目: crlDistributionPoints
, calIssuers
和 OCSP
URI。 (由 Christian Heimes 在 bpo-18379 [https://bugs.python.org/issue?@action=redirect&bpo=18379] 中贡献。)
stat
现在 stat
模块以 _stat
中的 C 实现作为后端。 C 实现是必需的因为大多数值都未被标准化并且依赖于平台。 (由 Christian Heimes 在 bpo-11016 [https://bugs.python.org/issue?@action=redirect&bpo=11016] 中贡献。)
该模块支持新的 ST_MODE
旗标, S_IFDOOR
, S_IFPORT
和 S_IFWHT
。 (由 Christian Hiemes 在 bpo-11016 [https://bugs.python.org/issue?@action=redirect&bpo=11016] 中贡献。)
struct
新增函数 iter_unpack
和在已编译格式上的新增方法 struct.Struct.iter_unpack()
提供了对包含给定格式数据的重复实例的缓冲区的流式解包功能。 (由 Antoine Pitrou 在 bpo-17804 [https://bugs.python.org/issue?@action=redirect&bpo=17804] 中贡献。)
subprocess
现在 check_output()
接受一个 input 参数用于为所运行的命令提供 stdin
的内容。 (由 Zack Weinberg 在 bpo-16624 [https://bugs.python.org/issue?@action=redirect&bpo=16624] 中贡献。)
现在 getstatus()
和 getstatusoutput()
已适用于 Windows。 这一修改是在 3.3.4 中意外实施的。 (由 Tim Golden 在 bpo-10197 [https://bugs.python.org/issue?@action=redirect&bpo=10197] 中贡献。)
sunau
现在 getparams()
方法将返回一个具名元组而不是普通元组。 (由 Claudiu Popa 在 bpo-18901 [https://bugs.python.org/issue?@action=redirect&bpo=18901] 中贡献。)
现在 sunau.open()
可支持上下文管理协议:当在 with
代码块中使用时,所返回对象的 close
方法将在代码块结束时被自动调用。 (由 Serhiy Storchaka 在 bpo-18878 [https://bugs.python.org/issue?@action=redirect&bpo=18878] 中贡献。)
现在 AU_write.setsampwidth()
已支持 24 位采样,因此增加了使用该模块写入 24 位采样的支持。 (由 Serhiy Storchaka 在 bpo-19261 [https://bugs.python.org/issue?@action=redirect&bpo=19261] 中贡献。)
现在 writeframesraw()
和 writeframes()
方法将接受任意 bytes-like object。 (由 Serhiy Storchaka 在 bpo-8311 [https://bugs.python.org/issue?@action=redirect&bpo=8311] 中贡献。)
sys
新增函数 sys.getallocatedblocks()
可返回当前由解释器所分配的内存块数量。 (在使用默认 --with-pymalloc
设置的 CPython 中,这将是通过 PyObject_Malloc()
API 执行的分配。) 这在追踪内存泄漏时会很有用处,特别是对于通过测试套件自动追踪的场景。 (由 Antoine Pitrou 在 bpo-13390 [https://bugs.python.org/issue?@action=redirect&bpo=13390] 中贡献。)
当 Python 解释器以 交互模式 启动时,它会检查 sys
模块中的 __interactivehook__
属性。 如果该属性存在,它的值将在交互模式启动之前不附带参数地被调用。 这个检查是在读取 PYTHONSTARTUP
文件之后进行的,因此可以在那里设置它。 site
模块会在平台支持 readline
的情况下 把它设置为 一个启用制表符补全和历史记录保存(在 ~/.python-history
中)的函数。 如果你不想要这个(新增的)行为,可以通过从 sys
中删除这个属性(或将其设为其他可调用对象)在 PYTHONSTARTUP
, sitecustomize
或 usercustomize
中覆盖它。 (由 Éric Araujo 和 Antoine Pitrou 在 bpo-5845 [https://bugs.python.org/issue?@action=redirect&bpo=5845] 中贡献。)
tarfile
现在 tarfile
模块当直接作为脚本或通过 -m
调用时将支持简单的 命令行接口。 这可被用来创建和提取 tar 归档文件。 (由 Berker Peksag 在 bpo-13477 [https://bugs.python.org/issue?@action=redirect&bpo=13477] 中贡献。)
textwrap
TextWrapper
类新增了两个属性/构造器参数: max_lines
,用来限制输出的行数,以及 placeholder
,它是一个当输出由于 max_lines 限制被截断时将出现在输出末尾处的字符串。 一个在此功能之上新增的便捷函数 shorten()
可将输入中的所有空格压缩为单个空格并产生一个宽度为 width 并以 placeholder (默认为 […]
) 结束的单独行。 (由 Antoine Pitrou 和 Serhiy Storchaka 在 bpo-18585 [https://bugs.python.org/issue?@action=redirect&bpo=18585] 和 bpo-18725 [https://bugs.python.org/issue?@action=redirect&bpo=18725] 中贡献。)
threading
代表可通过新增的 main_thread()
函数来获取的主线程的 Thread
对象。 在通常条件下这将是启动 Python 解释器所在的线程。 (由 Andrew Svetlov 在 bpo-18882 [https://bugs.python.org/issue?@action=redirect&bpo=18882] 中贡献。)
回溯
新增的 traceback.clear_frames()
函数可接受一个回溯对象清除它所引用的所有帧中的局部变量,以减少内存消耗量。 (由 Andrew Kuchling 在 bpo-1565525 [https://bugs.python.org/issue?@action=redirect&bpo=1565525] 中贡献。)
types
新增的 DynamicClassAttribute()
描述器提供了一种定义属性的方式,这种属性可正常地在实例对象中查找,但在类中查找时会被导向 类的 __getattr__
。 这将允许设置在类上激活的特征属性,并在相同名称的类上具有虚拟属性(参见 Enum
的例子)。 (由 Ethan Furman 在 bpo-19030 [https://bugs.python.org/issue?@action=redirect&bpo=19030] 中贡献。)
urllib
现在 urllib.request
支持 data:
使用 DataHandler
类的 URL。 (由 Mathias Panzenböck 在 bpo-16423 [https://bugs.python.org/issue?@action=redirect&bpo=16423] 中贡献。)
由 Request
类使用的 http 方法现在可通过在子类上设置 method
类属性来指定。 (由 Jason R Coombs 在 bpo-18978 [https://bugs.python.org/issue?@action=redirect&bpo=18978] 中贡献。)
现在 Request
对象是可重用的:如果 full_url
或 data
属性被修改,所有相关的内部特征属性都将被更新。 例如,这意味着现在可以在多个使用不同 data 参数的 OpenerDirector.open()
调用中使用相同的 Request
对象,或者修改 Request
的 url
而不必从头重新计算它们。 此外还有新增的 remove_header()
方法可被用来从 Request
中移除标头。 (由 Alexey Kachayev 在 bpo-16464 [https://bugs.python.org/issue?@action=redirect&bpo=16464] 中,Daniel Wozniak 在 bpo-17485 [https://bugs.python.org/issue?@action=redirect&bpo=17485] 中,以及 Damien Brecht 和 Senthil Kumaran 在 bpo-17272 [https://bugs.python.org/issue?@action=redirect&bpo=17272] 中贡献。)
现在 HTTPError
对象具有一个 headers
属性可提供对与错误相关的 HTTP 响应的访问。 (由 Berker Peksag 在 bpo-15701 [https://bugs.python.org/issue?@action=redirect&bpo=15701] 中贡献。)
unittest
TestCase
类有一个新方法 subTest()
,它可产生一个以 with
代码块作为“子测试”的上下文管理器。 这个上下文管理器允许测试方法通过调用一个循环内的 subTest
上下文管理器这样的方式动态生成子测试。 这样单个测试方法就可以产生无限多个单独标识并单独计数的测试,这些测试即使在其中一个或多个测试失败的情况下仍然会全部运行。 例如:
- class NumbersTest(unittest.TestCase):
- def test_even(self):
- for i in range(6):
- with self.subTest(i=i):
- self.assertEqual(i % 2, 0)
将得到六个子测试,在单元测试详细输出中各自以变量名 i
加该变量专属的值来标识 (i=0
, i=1
等等)。 该示例的完整版本见 使用子测试区分测试迭代。 (由 Antoine Pitrou 在 bpo-16997 [https://bugs.python.org/issue?@action=redirect&bpo=16997] 中贡献。)
现在 unittest.main()
接受一个包含测试名称的可迭代对象作为 defaultTest,而在之前版本中它只接受单个字符串形式的测试名称。 (由 Jyrki Pulliainen 在 bpo-15132 [https://bugs.python.org/issue?@action=redirect&bpo=15132] 中贡献。)
如果在测试发现期间(即在测试文件中的模块层级)引发了 SkipTest
,现在它将被报告为跳过而不是错误。 (由 Zach Ware 在 bpo-16935 [https://bugs.python.org/issue?@action=redirect&bpo=16935] 中贡献。)
现在 discover()
会对所发现的文件进行排序以提供一致的测试顺序。 (由 Martin Melin 和 Jeff Ramnani 在 bpo-16709 [https://bugs.python.org/issue?@action=redirect&bpo=16709] 中贡献。)
如果测试成功,现在 TestSuite
会在测试完成运行时立即丢弃对测试的引用。 在支持垃圾回收的 Python 解释器上,这允许当没有其他对象持有对测试的引用时将该测试作为垃圾回收。 可以通过创建一个定义了自定义 _removeTestAtIndex
方法的 TestSuite
子类来覆盖此行为。 (由 Tom Wardill, Matt McClure 和 Andrew Svetlov 在 bpo-11798 [https://bugs.python.org/issue?@action=redirect&bpo=11798] 中贡献。)
新增的测试断言上下文管理器 assertLogs()
将确保给定的代码块使用 logging
模块发出日志记录消息。 在默认情况下消息可来自任意日志记录器并具有 INFO
或更高的优先级,但要指明日志记录器名称和替代的最低日志级别。 可以在该上下文管理器所返回的对象中查询 LogRecord
和/或所记录的已格式化消息。 (由 Antoine Pitrou 在 bpo-18937 [https://bugs.python.org/issue?@action=redirect&bpo=18937] 中贡献。)
现在测试发现将可用于命名空间包(由 Claudiu Popa 在 bpo-17457 [https://bugs.python.org/issue?@action=redirect&bpo=17457] 中贡献。).) 现在 unittest.mock
对象可以在匹配调用时检查其规范签名,这意味着现在可以通过位置或名称来匹配参数,而不是仅能通过位置。 (由 Antoine Pitrou 在 bpo-17015 [https://bugs.python.org/issue?@action=redirect&bpo=17015] 中贡献。)
现在 mock_open()
对象具有 readline
和 readlines
方法。 (由 Toshio Kuratomi 在 bpo-17467 [https://bugs.python.org/issue?@action=redirect&bpo=17467] 中贡献。)
venv
现在 venv
包括了用于 csh
和 fish
shell 的激活脚本。 (由 Andrew Svetlov 在 bpo-15417 [https://bugs.python.org/issue?@action=redirect&bpo=15417] 中贡献。)
EnvBuilder
和 create()
便捷函数接受新的关键字参数 with_pip,默认值为 False
,它控制 EnvBuilder
是否确保 pip
在虚拟环境中安装。 (作为 PEP 453 [https://peps.python.org/pep-0453/] 实现的组成部分由 Nick Coghlan 在 bpo-19552 [https://bugs.python.org/issue?@action=redirect&bpo=19552] 中贡献。)
wave
现在 getparams()
方法将返回一个具名元组而不是普通元组。 (由 Claudiu Popa 在 bpo-17487 [https://bugs.python.org/issue?@action=redirect&bpo=17487] 中贡献。)
现在 wave.open()
已支持上下文管理器协议。 (由 Claudiu Popa 在 bpo-17616 [https://bugs.python.org/issue?@action=redirect&bpo=17616] 中贡献。)
现在 wave
可以 将输出写入到不可定位的文件。 (由 David Jones, Guilherme Polo 和 Serhiy Storchaka 在 bpo-5202 [https://bugs.python.org/issue?@action=redirect&bpo=5202] 中贡献。)
现在 writeframesraw()
和 writeframes()
方法将接受任意 bytes-like object。 (由 Serhiy Storchaka 在 bpo-8311 [https://bugs.python.org/issue?@action=redirect&bpo=8311] 中贡献。)
weakref
新增的 WeakMethod
类可模拟指向绑定方法的弱引用。 (由 Antoine Pitrou 在 bpo-14631 [https://bugs.python.org/issue?@action=redirect&bpo=14631] 中贡献。)
新增的 finalize
类使得注册一个当对象被作为垃圾回收时唤起的回调成为可能,而无需小心地管理弱引用本身的生命周期。 (由 Richard Oudkerk 在 bpo-15528 [https://bugs.python.org/issue?@action=redirect&bpo=15528] 中贡献。)
如果存在任何与 ref
相关联的回调,现在将通过 __callback__
属性对外公开。 (由 Mark Dickinson 在 bpo-17643 [https://bugs.python.org/issue?@action=redirect&bpo=17643] 中贡献。)
xml.etree
新增的解析器 XMLPullParser
允许用非阻塞的应用程序来解析 XML 文档。 相关示例可参见 用于非阻塞解析的拉取 API。 (由 Antoine Pitrou 在 bpo-17741 [https://bugs.python.org/issue?@action=redirect&bpo=17741] 中贡献。)
现在 xml.etree.ElementTree
tostring()
和 tostringlist()
函数,以及 ElementTree
的 write()
方法都具有一个 short_empty_elements 仅限关键字形参 用来提供对于无内容的元素要采取缩写 (
) 还是扩展 (
) 形式的控制。 (由 Ariel Poliak 和 Serhiy Storchaka 在 bpo-14377 [https://bugs.python.org/issue?@action=redirect&bpo=14377] 中贡献。)
zipfile
PyZipFile
类的 writepy()
方法新增的 filterfunc 选项可用来控制要将哪些目录添加到归档中。 例如,可以用它将测试文件排除在归档之外。 (由 Christian Tismer 在 bpo-19274 [https://bugs.python.org/issue?@action=redirect&bpo=19274] 中贡献。)
现在 ZipFile
和 PyZipfile
的 allowZip64 形参默认值为 True
。 (由 William Mallard 在 bpo-17201 [https://bugs.python.org/issue?@action=redirect&bpo=17201] 中贡献。)
CPython 实现的变化
PEP 445: 自定义 CPython 内存分配器
PEP 445 [https://peps.python.org/pep-0445/] 添加了新的 C 层级接口用来在 CPython 解释器中对内存分配进行自定义。
参见
- PEP 445 [https://peps.python.org/pep-0445/] — 新增用于自定义 Python 内存分配器的 API
- PEP 由 Victor Stinner 撰写并实现。
PEP 442: 安全的对象最终化
PEP 442 [https://peps.python.org/pep-0442/] 移除了 CPython 中有关对象最终化的限制和特殊处理。 有了它,具有 __del__()
方法的对象,以及具有 finally
子句的生成器在有循环引用的情况下也可以被最终化。
作为此项改变的一部分,大多数情况下在解释器关闭期间模块的全局变量不会被强制设为 None
,而是取决于循环垃圾回收器的正常操作。 这避免了大量的解释器关闭时错误,这类错误通常都涉及 __del__
方法,它们自循环 GC 首次被引入起就一直困扰着 Python。
参见
- PEP 442 [https://peps.python.org/pep-0442/] — 安全的对象最终化
- PEP 由 Antoine Pitrou 撰写并实现
PEP 456: 安全且可互换的哈希算法
PEP 456 [https://peps.python.org/pep-0456/] 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 [https://bugs.python.org/issue?@action=redirect&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 [https://peps.python.org/pep-0436/]) 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 [https://peps.python.org/pep-0436/] — 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 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=16129].)Most Python C APIs that don't mutate string arguments are now correctly marked as accepting
const char *
rather thanchar *
. (Contributed by Serhiy Storchaka in bpo-1772673 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=7330].)New function
PyStructSequence_InitType2()
supplements the existingPyStructSequence_InitType()
function. The difference is that it returns0
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 [https://bugs.python.org/issue?@action=redirect&bpo=18596].)
The Windows build now uses Address Space Layout Randomization [https://en.wikipedia.org/wiki/Address_space_layout_randomization] and Data Execution Prevention [https://en.wikipedia.org/wiki/Data_Execution_Prevention]. (Contributed by Christian Heimes in bpo-16632 [https://bugs.python.org/issue?@action=redirect&bpo=16632].)
New function
PyObject_LengthHint()
is the C API equivalent ofoperator.length_hint()
. (Contributed by Armin Ronacher in bpo-16148 [https://bugs.python.org/issue?@action=redirect&bpo=16148].)
其他改进
The python command has a new option,
-I
, which causes it to run in "isolated mode", which means thatsys.path
contains neither the script's directory nor the user'ssite-packages
directory, and allPYTHON*
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 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=5845].)Invoking the Python interpreter with
--version
now outputs the version to standard output instead of standard error (bpo-18338 [https://bugs.python.org/issue?@action=redirect&bpo=18338]). Similar changes were made toargparse
(bpo-18920 [https://bugs.python.org/issue?@action=redirect&bpo=18920]) and other modules that have script-like invocation capabilities (bpo-18922 [https://bugs.python.org/issue?@action=redirect&bpo=18922]).The CPython Windows installer now adds
.py
to thePATHEXT
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 [https://bugs.python.org/issue?@action=redirect&bpo=18569].)A new
make
target coverage-report [https://devguide.python.org/coverage/#measuring-coverage-of-c-code-with-gcov-and-lcov] will build python, run the test suite, and generate an HTML coverage report for the C codebase usinggcov
and lcov [https://github.com/linux-test-project/lcov].The
-R
option to the python regression test suite now also checks for memory allocation leaks, usingsys.getallocatedblocks()
. (Contributed by Antoine Pitrou in bpo-13390 [https://bugs.python.org/issue?@action=redirect&bpo=13390].)现在
python -m
将可用于命名空间包。现在
stat
模块是用 C 实现的,这意味着它将从 C 头文件中获取其常量值,而不是像之前版本中那样将值码编码在 python 模块中。现在将能够正确地从单个 OS 模块加载多个 (
.so
,.dll
) python 模块(在之前版本中则会静默地返回文件中的第一个 python 模块)。 (由 Václav Šmilauer 在 bpo-16421 [https://bugs.python.org/issue?@action=redirect&bpo=16421] 中贡献。)A new opcode,
LOAD_CLASSDEREF
, has been added to fix a bug in the loading of free variables in class bodies that could be triggered by certain uses of prepare. (Contributed by Benjamin Peterson in bpo-17853 [https://bugs.python.org/issue?@action=redirect&bpo=17853].)多个有关 MemoryError 的崩溃问题被 Victor Stinner 使用他基于 PEP 445 [https://peps.python.org/pep-0445/] 的
pyfailmalloc
工具加以确定并修复 (bpo-18408 [https://bugs.python.org/issue?@action=redirect&bpo=18408], bpo-18520 [https://bugs.python.org/issue?@action=redirect&bpo=18520])。现在
pyvenv
命令接受一个--copies
选项以使用拷贝而不是符号链接,即使在默认使用符号链接的系统上也是如此。 (由 Vinay Sajip 在 bpo-18807 [https://bugs.python.org/issue?@action=redirect&bpo=18807] 中贡献。)pyvenv
命令也接受一个--without-pip
选项用来抑制在其他情况下将自动将 pip 初始设置到虚拟环境中。 (作为 PEP 453 [https://peps.python.org/pep-0453/] 实现的一部分由 Nick Coghlan 在 bpo-19552 [https://bugs.python.org/issue?@action=redirect&bpo=19552] 中贡献。)现在编码格式名称在
PYTHONIOENCODING
环境变量的设置值中将为可选项。 这使得只设置错误处理器而不改变默认编码格式成为可能。 (由 Serhiy Storchaka 在 bpo-18818 [https://bugs.python.org/issue?@action=redirect&bpo=18818] 中贡献。)现在
bz2
,lzma
, andgzip
模块的open
函数已支持x
(独占式创建) 模式。 (由 Tim Heaney 和 Vajrasky Kok 在 bpo-19201 [https://bugs.python.org/issue?@action=redirect&bpo=19201], bpo-19222 [https://bugs.python.org/issue?@action=redirect&bpo=19222] 和 bpo-19223 [https://bugs.python.org/issue?@action=redirect&bpo=19223] 中贡献。)
显著的优化
现在 UTF-32 解码器获得了 3x 至 4x 的提速。 (由 Serhiy Storchaka 在 bpo-14625 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&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
andlocale
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 [https://bugs.python.org/issue?@action=redirect&bpo=19219], bpo-19218 [https://bugs.python.org/issue?@action=redirect&bpo=19218], bpo-19209 [https://bugs.python.org/issue?@action=redirect&bpo=19209], bpo-19205 [https://bugs.python.org/issue?@action=redirect&bpo=19205] and bpo-9548 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=16034].)random.getrandbits()
is 20%-40% faster for small integers (the most common use case). (Contributed by Serhiy Storchaka in bpo-16674 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&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 throughsubprocess
. (Contributed by Richard Oudkerk in bpo-15758 [https://bugs.python.org/issue?@action=redirect&bpo=15758].)现在
html.escape()
获得了 10x 速度提升。 (由 Matt Bryant 在 bpo-18020 [https://bugs.python.org/issue?@action=redirect&bpo=18020] 中贡献。)在 Windows 上,现在将使用原生的
VirtualAlloc
而不是obmalloc
中的 CRTmalloc
。 人工基准测试显示可节省约 3% 的内存。现在
os.urandom()
会使用延迟打开的持久性文件描述符以避免在从多个线程并行时使用过多的文件描述符。 (由 Antoine Pitrou 在 bpo-18756 [https://bugs.python.org/issue?@action=redirect&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 byimportlib.util.find_spec()
;importlib.machinery.PathFinder.find_module()
is replaced byimportlib.machinery.PathFinder.find_spec()
;importlib.abc.MetaPathFinder.find_module()
is replaced byimportlib.abc.MetaPathFinder.find_spec()
;importlib.abc.PathEntryFinder.find_loader()
andfind_module()
are replaced byimportlib.abc.PathEntryFinder.find_spec()
; all of thexxxLoader
ABCload_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 anexec_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; andimportlib.abc.Loader.module_repr()
,importlib.util.module_for_loader()
,importlib.util.set_loader()
, andimportlib.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 中移除。HTMLParser
的 strict 参数已被弃用。plistlib
readPlist()
,writePlist()
,readPlistFromBytes()
和writePlistToBytes()
等函数已被弃用而应改用相应的新函数load()
,dump()
,loads()
和dumps()
。Data()
已被弃用而应直接使用bytes
构造器。sysconfig
的键SO
已被弃用,它已被EXT_SUFFIX
所替代。各种
open
函数所接受的U
模式已被弃用。 在 Python3 中它已不再有任何实际作用,并应当改用适当的io.TextIOWrapper
(如有必要) 及其 newline 参数。xml.etree.ElementTree.iterparse()
的 parser 参数,就如XMLParser()
的 html 参数一样。 要对后者的移除做好准备,所有XMLParser
的参数都应当以关键字形式传入。
弃用的特性
运行 IDLE —- Python editor and shell 时附带
-n
旗标(无子进程)的做法已被弃用。 但是,该特性在 bpo-18823 [https://bugs.python.org/issue?@action=redirect&bpo=18823] 解决之前将不会被移除。site 模块在 "site-python" 目录存在的情况下 sys.path 添加该目录的做法已被弃用 (bpo-19375 [https://bugs.python.org/issue?@action=redirect&bpo=19375])。
移除
不再支持的操作系统
从源代码和构建工具中删除了对以下操作系统的支持:
OS/2 (bpo-16135 [https://bugs.python.org/issue?@action=redirect&bpo=16135]).
Windows 2000(变更集e52df05b496a)。
Windows系统中
COMSPEC
指向command.com
的版本( bpo-14470 [https://bugs.python.org/issue?@action=redirect&bpo=14470] )。VMS (bpo-16136 [https://bugs.python.org/issue?@action=redirect&bpo=16136]).
API 与特性的移除
以下过时并在之前版本中弃用的 API 和特性现已被移除:
不再继续维护的
Misc/TextMate
和Misc/vim
目录已被移除(请参阅 devguide [https://devguide.python.org] 了解相关替代器的使用建议)。SO
makefile 宏已被移除(被SHLIB_SUFFIX
和EXT_SUFFIX
宏所替代) (bpo-16754 [https://bugs.python.org/issue?@action=redirect&bpo=16754])。PyThreadState.tick_counter
字段已被移除;该字段值自 Python 3.2 即 "新 GIL" 被引入时起就不再有意义了 (bpo-19199 [https://bugs.python.org/issue?@action=redirect&bpo=19199])。PyLoader
和PyPycLoader
已从importlib
中移除。 (由 Taras Lyapun 在 bpo-15641 [https://bugs.python.org/issue?@action=redirect&bpo=15641] 中贡献。)HTTPConnection
和HTTPSConnection
的 strict 参数已被移除。 HTTP 0.9 风格的 "简单响应" 不再受到支持。被弃用的
urllib.request.Request
读取和设置方法add_data
,has_data
,get_data
,get_type
,get_host
,get_selector
,set_proxy
,get_origin_req_host
和is_unverifiable
已被移除(请改为直接属性访问)。对加载已弃用的
TYPE_INT64
的支持已从marshal
中被移除。 (由 Dan Riti 在 bpo-15480 [https://bugs.python.org/issue?@action=redirect&bpo=15480] 中贡献。)inspect.Signature
: 仅限位置形参现在需要有一个合法的名称。object.__format__()
no longer accepts non-empty format strings, it now raises aTypeError
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 aTypeError
if you are using an's'
format code with objects that do not have a format method that handles it. See bpo-7994 [https://bugs.python.org/issue?@action=redirect&bpo=7994] for background.difflib.SequenceMatcher.isbjunk()
和difflib.SequenceMatcher.isbpopular()
已在 3.2 中被弃用,现在已被移除:请使用x in sm.bjunk
和x in sm.bpopular
,其中 sm 是一个SequenceMatcher
对象 (bpo-13248 [https://bugs.python.org/issue?@action=redirect&bpo=13248])。
代码清理
未被使用并且未写入文档的内部
Scanner
类已从pydoc
模块中移除。私有并且实际未使用的
_gestalt
模块已被移除,同时移除了私有的platform
函数macver_lookup
,macver_gstalt
和_bcd2str
,它们仅会在严重过时的 OSX 系统上被调用 (参见 bpo-18393 [https://bugs.python.org/issue?@action=redirect&bpo=18393])。
移植到 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, settingPYTHONPATH
to an empty value was not equivalent to not setting it at all: settingPYTHONPATH
to an empty value was equivalent to setting it to.
, which leads to confusion when reasoning by analogy to howPATH
works. The behavior now conforms to the posix convention forPATH
.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 [https://bugs.python.org/issue?@action=redirect&bpo=17323].)The python command and most stdlib scripts (as well as
argparse
) now output--version
information tostdout
instead ofstderr
(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 raisingNotImplementedError
blindly. This will only affect code callingsuper()
and falling through all the way to the ABCs. For compatibility, catch bothNotImplementedError
or the appropriate exception as needed.The module type now initializes the
__package__
and__loader__
attributes toNone
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 [https://bugs.python.org/issue?@action=redirect&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 useimportlib.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 reloaded (bpo-19413 [https://bugs.python.org/issue?@action=redirect&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 usehasattr(module, '__path__')
(bpo-18065 [https://bugs.python.org/issue?@action=redirect&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 ofimportlib.machinery.FrozenImporter
, or if Python 2 compatibility is necessary you can useimp.is_frozen()
.py_compile.compile()
now raisesFileExistsError
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 raisesImportError
when the source code being loaded triggers aSyntaxError
orUnicodeDecodeError
. AsImportError
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()
andfunctools.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 useinspect.unwrap()
to access the first function in the chain that has no__wrapped__
attribute.inspect.getfullargspec()
has been reimplemented on top ofinspect.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 thatinspect.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 insys.path_hooks
for the empty string. This results insys.path_importer_cache
never containing''
, thus iterating throughsys.path_importer_cache
based onsys.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 [https://bugs.python.org/issue?@action=redirect&bpo=18416]). is specified on the commandline) (bpo-18416 [https://bugs.python.org/issue?@action=redirect&bpo=18416]).The removal of the strict argument to
HTTPConnection
andHTTPSConnection
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 aSyntaxError
. 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 [https://bugs.python.org/issue?@action=redirect&bpo=17434]).ssl.SSLSocket.getpeercert()
andssl.SSLSocket.do_handshake()
now raise anOSError
withENOTCONN
when theSSLSocket
is not connected, instead of the previous behavior of raising anAttributeError
. In addition,getpeercert()
will raise aValueError
if the handshake has not yet been done.base64.b32decode()
now raises abinascii.Error
when the input string contains non-b32-alphabet characters, instead of aTypeError
. This particularTypeError
was missed when the otherTypeError
s were converted. (Contributed by Serhiy Storchaka in bpo-18011 [https://bugs.python.org/issue?@action=redirect&bpo=18011].) Note: this change was also inadvertently applied in Python 3.3.3.The
file
attribute is now automatically closed when the creatingcgi.FieldStorage
instance is garbage collected. If you were pulling the file object out separately from thecgi.FieldStorage
instance and not keeping the instance alive, then you should either store the entirecgi.FieldStorage
instance or read the contents of the file before thecgi.FieldStorage
instance is garbage collected.Calling
read
orwrite
on a closed SSL socket now raises an informativeValueError
rather than the previous more mysteriousAttributeError
(bpo-9177 [https://bugs.python.org/issue?@action=redirect&bpo=9177]).slice.indices()
no longer produces anOverflowError
for huge values. As a consequence of this fix,slice.indices()
now raises aValueError
if given a negative length; previously it returned nonsense values (bpo-14794 [https://bugs.python.org/issue?@action=redirect&bpo=14794]).The
complex
constructor, unlike thecmath
functions, was incorrectly acceptingfloat
values if an object's__complex__
special method returned one. This now raises aTypeError
. (bpo-16290 [https://bugs.python.org/issue?@action=redirect&bpo=16290].)The
int
constructor in 3.2 and 3.3 erroneously acceptsfloat
values for the base parameter. It is unlikely anyone was doing this, but if so, it will now raise aTypeError
(bpo-16772 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=17094].)Parameter names in
__annotations__
dicts are now mangled properly, similarly to__kwdefaults__
. (Contributed by Yury Selivanov in bpo-20625 [https://bugs.python.org/issue?@action=redirect&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 [https://bugs.python.org/issue?@action=redirect&bpo=18532]).Because
unittest.TestSuite
now drops references to tests after they are run, test harnesses that reuse aTestSuite
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 thatunittest
is designed to provide. However, if the lack of isolation is considered acceptable, the old behavior can be restored by creating aTestSuite
subclass that defines a_removeTestAtIndex
method that does nothing (seeTestSuite.__iter__()
) (bpo-11798 [https://bugs.python.org/issue?@action=redirect&bpo=11798]).unittest
now usesargparse
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()
, andre.sub()
functions, and thegroup()
andgroups()
methods ofmatch
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, abytearray
, 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 [https://bugs.python.org/issue?@action=redirect&bpo=16685]).The new convert_charrefs argument to
HTMLParser
currently defaults toFalse
for backward compatibility, but will eventually be changed to default toTrue
. It is recommended that you add this keyword, with the appropriate value, to anyHTMLParser
calls in your code (bpo-13633 [https://bugs.python.org/issue?@action=redirect&bpo=13633]).Since the digestmod argument to the
hmac.new()
function will in the future have no default, all calls tohmac.new()
should be changed to explicitly specify a digestmod (bpo-17276 [https://bugs.python.org/issue?@action=redirect&bpo=17276]).Calling
sysconfig.get_config_var()
with theSO
key, or lookingSO
up in the results of a call tosysconfig.get_config_vars()
is deprecated. This key should be replaced byEXT_SUFFIX
orSHLIB_SUFFIX
, depending on the context (bpo-19555 [https://bugs.python.org/issue?@action=redirect&bpo=19555]).Any calls to
open
functions that specifyU
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 inTextIOWrapper
to use its newline argument (bpo-15204 [https://bugs.python.org/issue?@action=redirect&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()
andjson.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 [https://bugs.python.org/issue?@action=redirect&bpo=16333]).现在
doctest
会在扩展模块的__doc__
字符串中寻找 doctest,因此如果你的 doctest 测试发现包括具有类似 doctest 内容的扩展模块那么你可能会遇到在你之前运行测试时从未遇到过的测试失败 (bpo-3158 [https://bugs.python.org/issue?@action=redirect&bpo=3158])。作为 Python 启动过程改进的一部分
collections.abc
模块进行了小幅度的重构。 作为此项重构的结果,导入collections
将不再自动导入collections.abc
。 如果你的程序依赖于这个(未写入文档的)隐式导入,你将需要添加显式的import collections.abc
(bpo-20784 [https://bugs.python.org/issue?@action=redirect&bpo=20784])。
C API 的变化
PyEval_EvalFrameEx()
,PyObject_Repr()
, andPyObject_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 withPyErr_Fetch()
or is being deliberately replaced with a different exception), an explicitPyErr_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 [https://bugs.python.org/issue?@action=redirect&bpo=16742])现在
PyThread_set_key_value()
总是会设置值。 在 Python 3.3 中,如果键已存在(如果当前值为非NULL
指针)该函数将不执行任何操作。PyFrameObject
结构体的f_tstate
(线程状态) 字段已被移除以修复一个程序错误;相关理由参见 bpo-14432 [https://bugs.python.org/issue?@action=redirect&bpo=14432]。
3.4.3 的变化
PEP 476: 默认为 stdlib http 客户端启用证书验证
http.client
及其他依赖它的模块,比如 urllib.request
和 xmlrpc.client
,现在将验证服务器是否提供了由平台信任的仓库中的 CA 签名的证书并且其主机名与默认被请求的主机名相匹配,这将显著提升许多应用程序的安全性。
对于需要之前版本的旧有行为的应用程序,可以传入一个替代的上下文:
- import urllib.request
- import ssl
- # 这将禁用所有验证
- context = ssl._create_unverified_context()
- # 这将允许为主机使用指定证书,
- # 它无须位于受信任的证书存储库中
- context = ssl.create_default_context(cafile="pathto/file.crt")
- urllib.request.urlopen("https://invalid-cert", context=context)