- Python 3.3 有什么新变化
- Python 3.3 有什么新变化
- 摘要 — 发布重点
- PEP 405: 虚拟环境
- PEP 420: 隐式命名空间包
- PEP 3118: 新的内存视图实现和缓冲协议文档
- PEP 393: 灵活的字符串表示
- PEP 397: 适用于Windows的Python启动器
- PEP 3151: 重写 OS 和 IO 异常的层次结构
- PEP 380: 委托给子生成器的语法
- PEP 409: 清除异常上下文
- PEP 414: 显式的Unicode文本
- PEP 3155: 类和函数的限定名称
- PEP 412: Key-Sharing Dictionary
- PEP 362: 函数签名对象
- PEP 421: 添加 sys.implementation
- 使用 importlib 作为导入的实现
- 其他语言特性修改
- A Finer-Grained Import Lock
- Builtin functions and types
- 新增模块
- 改进的模块
Python 3.3 有什么新变化
Python 3.3 有什么新变化
本文介绍了 Python 3.3 相比 3.2 的新增特性。 Python 3.3 于 2012 年 9 月 29 日 发布。 有关完整详细信息,请参见 changelog。
参见
PEP 398 - Python 3.3 发布计划
摘要 — 发布重点
新的语法特性:
-
新增
yield from表达式用于 生成器委托。 -
u'unicode'语法重新被接受用于 str 对象。
新的库模块:
-
faulthandler (帮助调试低层级的崩溃)
-
ipaddress (代表 IP 地址和掩码的高层级对象)
-
lzma (使用 XZ / LZMA 算法压缩数据)
-
unittest.mock (使用模拟对象替换你的受测试系统中的某些部分)
-
venv (Python 虚拟环境,类似于流行的
virtualenv包)
新的内置特性:
- 重写 I/O 异常的层次结构.
实现的改进:
-
基于 importlib 重写 import machinery
-
更紧凑的 Unicode 字符串。
-
更紧凑的 属性字典。
显著改进的库模块:
-
针对 decimal 模块的 C 加速器。
-
email 模块中更好的 Unicode 处理 (暂定)。
安全改进:
- 哈希随机化被默认启用。
请继续阅读有关面向用户的改变的详细清单。
PEP 405: 虚拟环境
虚拟环境有助于创建 独立的 Python 设置,同时共享全系统的基础安装,便于维护。 虚拟环境有自己的私有站点包(即本地安装的库),并可选择与系统范围的站点包分离。 虚拟环境的概念和实现 受到流行的virtualenv 第三方 包 的启发,但受益于与解释器 核心更紧密的集成。
本 PEP 添加了 venv 模块用于编程访问,以及 pyvenv 脚本用于命令在线访问和管理。 Python 解释器会检查 pyvenv.cfg,文件的存在标志着虚拟环境目录树的基础。
参见
PEP 405 - Python虚拟环境
PEP 由 Carl Meyer 撰写 ; 由 Carl Meyer 和 Vinay Sajip 实现。
PEP 420: 隐式命名空间包
原生支持不要求 __init__.py 标记文件和可以自动跨越多个路径节的包目录(灵感来自多个命名空间包的第三方方案,如 PEP 420 中所述)
参见
PEP 420 - 隐式命名空间包
PEP 由 Eric V. Smith 撰写,由 Eric V. Smith 和 Barry Warsaw 实现
PEP 3118: 新的内存视图实现和缓冲协议文档
PEP 3118 的实现已获得大幅改进。
新的 memoryview 实现全面修复了 Py_buffer 结构体中曾导致多起崩溃报告的动态分配字段的所有权和生命周期问题。 此外,还修复了多个函数在非连续或多维输入时崩溃或返回不正确结果的问题。
现在 memoryview 对象具有符合 PEP-3118 标准的 getbufferproc(),可以检查使用者的请求类型。 新增了许多新的特性,其中的大部分已适用于非连续数组和带有子偏移量的数组。
文档已进行更新,清楚地列出了导出方和使用方的责任。 缓冲区请求旗标志被划分为基本旗标和复合旗标。 对非连续和多维的 NumPy 风格数组的内存布局进行了说明。
相关特性
-
现在 struct 模块语法中所有原生单字符格式指示符(可以选择添加 ‘@’ 前缀)均受到支持。
-
在某些限制条件下,cast() 方法允许改变 C 连续数组的格式和形状。
-
任何数组类型都支持多维列表的表示形式。
-
任何数组类型都支持多维比较操作。
-
格式为 B、b 或 c 的可哈希(只读)类型的一维 memoryview 现在将是可哈希的。 (由 Antoine Pitrou 在 bpo-13411 中贡献。)
-
支持对 1 维数据类型的任意切片。 例如,现在可以通过使用负步长值以 O(1) 复杂度对 memoryview 进行翻转。
API 的变化
-
官方的最大维度数量限制已更改为 64。
-
空形状、区间和子偏移量的表示形式现在是空元组而不是
None。 -
现在对格式为 ‘B’ (无符号字节型) 的 memoryview 元素的访问将返回一个整数(遵循结构体模块语法)。 要返回字节串对象则必须先将视图强制转换为 ‘c’。
-
现在 memoryview 比较将使用操作数的逻辑结构并会按值来比较所有数组元素。 结构体模块语法中的所有格式化字符串均受到支持。 带有不可识别的格式化字符串的视图仍然被允许,但无论视图内容如何比较结果总是不相等。
-
更多改变请参阅 Build and C API Changes 和 Porting C code。
(由 Stefan Krah 在 bpo-10181 中贡献。)
参见
PEP 3118 - 修改缓冲区协议
PEP 393: 灵活的字符串表示
Unicode字符串类型已改为支持多种内部表示法,具体取决于所表示的字符串中具有最大 Unicode 序号(1、2 或 4 字节)的字符 。 这样,在常见情况下可以节省空间,但在所有系统上都能使用完整的 UCS-4。 对于使用现有应用程序接口的兼容性 来说,可能会并行存在几种表示法;随着时间的推移,这种兼容性 应逐步淘汰。
在 Python 一方,此项改变应当没有任何缺点。
在 C API 方面,PEP 393 完全向下兼容。 旧的 API 至少还能使用五年。 使用传统 API 的应用程序不会完全受益于内存的减少,或者更糟的是,可能会使用更多的内存,因为 Python 可能需要维护每个字符串的两个版本(传统格式和新的高效存储)。
功能
由 PEP 393 引入的改变如下:
-
Python 现在始终支持全部 Unicode 码位,包括非 BMP 码位 (即从
U+0000到U+10FFFF)。 窄编译版本和宽编译版本之间的区别已不复存在,Python 现在的行为就像宽编译版本,甚至在 Windows 下也是如此。 -
随着窄编译版本的消亡,窄编译版本特有的问题也得到了解决,例如:
-
现在 len() 对于非 BMP 字符总是返回 1,因此
len('\U0010FFFF') == 1; -
替换对不会在字符串字面值中重新合并,因此
'\uDBFF\uDFFF' != '\U0010FFFF'; -
索引或切分非 BMP 字符会返回预期的值,因此
'\U0010FFFF'[0]现在会返回'\U0010FFFF'而不是'\uDBFF'; -
标准库中的所有其他函数现在都能正确处理非 BMP 代码点。
-
-
sys.maxunicode 的值现在总是
1114111(十六进制为0x10FFFF)。PyUnicode_GetMax()函数仍返回0xFFFF或0x10FFFF以便向下兼容,但不应与新的 Unicode API 一起使用 (参见 bpo-13054)。 -
./configure标志--with-wide-unicode已被移除。
性能和资源使用情况
现在,Unicode 字符串的存储取决于字符串中的最高码位:
-
纯 ASCII 和 Latin1 字符串 (
U+0000-U+00FF) 每个码位使用 1 个字节; -
BMP 字符串 (
U+0000-U+FFFF) 每个码位使用 2 个字节; -
非 BMP 字符串 (
U+10000-U+10FFFF) 每个码位使用 4 个字节。
这样做的效果是,对于大多数应用而言,字符串存储的内存使用量应该会大幅减少 —— 尤其是与以前的宽 unicode 版本相比 —— 因为在许多情况下,即使在国际环境中,字符串也将是纯 ASCII 格式(因为许多字符串存储的是非人类语言数据,如 XML 片段、HTTP 标头、JSON 编码数据等)。 出于同样的原因,我们还希望它能提高非小应用程序的 CPU 缓存效率。 在 Django 基准测试中,Python 3.3 的内存使用量比 Python 3.2 少两到三倍,比 Python 2.7 略好一些(详情请参见 PEP)。
参见
PEP 393 - 灵活的字符串表示
PEP 由 Martin von Löwis 撰写 ; 由 Torsten Becker 和 Martin von Löwis 实现。
PEP 397: 适用于Windows的Python启动器
Python 3.3 的 Windows 安装程序现在包含一个 py 启动程序,可用于以版本无关的方式启动 Python 应用程序。
双击 *.py 文件时会隐式调用该启动器。 如果系统中只安装了一个 Python 版本,则将使用该版本运行文件。 如果安装了多个版本,则默认使用最新版本,但也可以通过在 Python 脚本中加入 Unix 风格的“shebang 行”来覆盖该版本。
启动器也可以作为 py 应用程序在命令行中显式使用。运行 py 遵循与隐式启动脚本相同的版本选择规则,但可以通过传递适当的参数来选择更具体的版本(例如,当 Python 2 也已安装时,使用 -3 来请求 Python 3;当安装了较新的 Python 版本时,使用 -2.6 来特别请求较早的 Python 版本)。
除了启动器之外,Windows 安装程序现在还包含一个选项,可将新安装的 Python 添加到系统 PATH 中。 (由 Brian Curtin 在 bpo-3561 中贡献)。
参见
PEP 397 - 适用于Windows的Python启动器
PEP 由 Mark Hammond 和 Martin v. Löwis 撰写 ; 由 Vinay Sajip实现。
启动器文档: 适用于Windows的Python启动器
安装器 PATH 修改: 查找Python可执行文件
PEP 3151: 重写 OS 和 IO 异常的层次结构
现在,由操作系统错误引发的异常层次结构既得到了简化,又更加精细。
您不必再为在 OSError、IOError、EnvironmentError、WindowsError、mmap.error、socket.error 或 select.error 之间选择合适的异常类型而烦恼。 所有这些异常类型现在都只有一个: OSError。 出于兼容性考虑,其他名称将作为别名保留。
此外,现在捕捉特定错误条件也更容易了。无需从 errno 模块中检查 errno 属性(或 args[0] )中的特定常量,您可以捕捉适当的 OSError 子类。可用的子类如下:
并且 ConnectionError 本身具有细粒度的子类:
有了新的异常,现在就可以避免 errno 的常见用法了。 例如,下面是为 Python 3.2 编写的代码:
from errno import ENOENT, EACCES, EPERM
try:
with open("document.txt") as f:
content = f.read()
except IOError as err:
if err.errno == ENOENT:
print("document.txt file is missing")
elif err.errno in (EACCES, EPERM):
print("You are not allowed to read document.txt")
else:
raise
现在无需导入 errno,也无需手动检查异常属性:
try:
with open("document.txt") as f:
content = f.read()
except FileNotFoundError:
print("document.txt file is missing")
except PermissionError:
print("You are not allowed to read document.txt")
参见
PEP 3151 - 重写 OS 和 IO 异常的层次结构
PEP 由 Antoine Pitrou 撰写并实现
PEP 380: 委托给子生成器的语法
PEP 380 增加了 yield from 表达式,允许 generator 将其部分操作委托给另一个生成器。 这样,包含 yield 的代码部分就可以被分解出来,放在另一个生成器中。 此外,还允许子生成器返回一个值,并将该值提供给委托生成器。
虽然 yield from 表达式主要用于委托给子生成器,但它实际上允许委托给任意子生成器。
对于简单的迭代器而言,yield from iterable 本质上只是 for item in iterable: yield item 的简写形式:
>>> def g(x):
... yield from range(x, 0, -1)
... yield from range(x)
...
>>> list(g(5))
[5, 4, 3, 2, 1, 0, 1, 2, 3, 4]
However, unlike an ordinary loop, yield from allows subgenerators to receive sent and thrown values directly from the calling scope, and return a final value to the outer generator:
>>> def accumulate():
... tally = 0
... while 1:
... next = yield
... if next is None:
... return tally
... tally += next
...
>>> def gather_tallies(tallies):
... while 1:
... tally = yield from accumulate()
... tallies.append(tally)
...
>>> tallies = []
>>> acc = gather_tallies(tallies)
>>> next(acc) # Ensure the accumulator is ready to accept values
>>> for i in range(4):
... acc.send(i)
...
>>> acc.send(None) # Finish the first tally
>>> for i in range(5):
... acc.send(i)
...
>>> acc.send(None) # Finish the second tally
>>> tallies
[6, 10]
The main principle driving this change is to allow even generators that are designed to be used with the send and throw methods to be split into multiple subgenerators as easily as a single large function can be split into multiple subfunctions.
参见
PEP 380 - 委托给子生成器的语法
PEP 由 Greg Ewing 撰写,由 Greg Ewing 实现。由 Renaud Blanch,Ryan Kelly 和 Nick Coghlan 集成到3.3,由 Zbigniew Jędrzejewski-Szmek 和 Nick Coghlan 编写文档
PEP 409: 清除异常上下文
PEP 409 introduces new syntax that allows the display of the chained exception context to be disabled. This allows cleaner error messages in applications that convert between exception types:
>>> class D:
... def __init__(self, extra):
... self._extra_attributes = extra
... def __getattr__(self, attr):
... try:
... return self._extra_attributes[attr]
... except KeyError:
... raise AttributeError(attr) from None
...
>>> D({}).x
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getattr__
AttributeError: x
Without the from None suffix to suppress the cause, the original exception would be displayed by default:
>>> class C:
... def __init__(self, extra):
... self._extra_attributes = extra
... def __getattr__(self, attr):
... try:
... return self._extra_attributes[attr]
... except KeyError:
... raise AttributeError(attr)
...
>>> C({}).x
Traceback (most recent call last):
File "<stdin>", line 6, in __getattr__
KeyError: 'x'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __getattr__
AttributeError: x
No debugging capability is lost, as the original exception context remains available if needed (for example, if an intervening library has incorrectly suppressed valuable underlying details):
>>> try:
... D({}).x
... except AttributeError as exc:
... print(repr(exc.__context__))
...
KeyError('x',)
参见
PEP 409 - 清除异常上下文
PEP 由 Ethan Furman 撰写 ,由 Ethan Furman 和 Nick Coghlan 实现。
PEP 414: 显式的Unicode文本
To ease the transition from Python 2 for Unicode aware Python applications that make heavy use of Unicode literals, Python 3.3 once again supports the “u“ prefix for string literals. This prefix has no semantic significance in Python 3, it is provided solely to reduce the number of purely mechanical changes in migrating to Python 3, making it easier for developers to focus on the more significant semantic changes (such as the stricter default separation of binary and text data).
参见
PEP 414 - 显式的Unicode文本
PEP 由 Armin Ronacher 撰写
PEP 3155: 类和函数的限定名称
Functions and class objects have a new qualname attribute representing the “path” from the module top-level to their definition. For global functions and classes, this is the same as name. For other functions and classes, it provides better information about where they were actually defined, and how they might be accessible from the global scope.
Example with (non-bound) methods:
>>> class C:
... def meth(self):
... pass
...
>>> C.meth.__name__
'meth'
>>> C.meth.__qualname__
'C.meth'
Example with nested classes:
>>> class C:
... class D:
... def meth(self):
... pass
...
>>> C.D.__name__
'D'
>>> C.D.__qualname__
'C.D'
>>> C.D.meth.__name__
'meth'
>>> C.D.meth.__qualname__
'C.D.meth'
Example with nested functions:
>>> def outer():
... def inner():
... pass
... return inner
...
>>> outer().__name__
'inner'
>>> outer().__qualname__
'outer.<locals>.inner'
The string representation of those objects is also changed to include the new, more precise information:
>>> str(C.D)
"<class '__main__.C.D'>"
>>> str(C.D.meth)
'<function C.D.meth at 0x7f46b9fe31e0>'
参见
PEP 3155 - 类和函数的限定名称
PEP 由 Antoine Pitrou 撰写并实现
PEP 412: Key-Sharing Dictionary
Dictionaries used for the storage of objects’ attributes are now able to share part of their internal storage between each other (namely, the part which stores the keys and their respective hashes). This reduces the memory consumption of programs creating many instances of non-builtin types.
参见
PEP 412 - Key-Sharing Dictionary
PEP 由 Mark Shannon 撰写并实现。
PEP 362: 函数签名对象
A new function inspect.signature() makes introspection of python callables easy and straightforward. A broad range of callables is supported: python functions, decorated or not, classes, and functools.partial() objects. New classes inspect.Signature, inspect.Parameter and inspect.BoundArguments hold information about the call signatures, such as, annotations, default values, parameters kinds, and bound arguments, which considerably simplifies writing decorators and any code that validates or amends calling signatures or arguments.
参见
PEP 362: - 函数签名对象
PEP 由 Brett Cannon,Yury Selivanov,Larry Hastings,Jiwon Seo 撰写,由 Yury Selivanov 实现
PEP 421: 添加 sys.implementation
A new attribute on the sys module exposes details specific to the implementation of the currently running interpreter. The initial set of attributes on sys.implementation are name, version, hexversion, and cache_tag.
The intention of sys.implementation is to consolidate into one namespace the implementation-specific data used by the standard library. This allows different Python implementations to share a single standard library code base much more easily. In its initial state, sys.implementation holds only a small portion of the implementation-specific data. Over time that ratio will shift in order to make the standard library more portable.
One example of improved standard library portability is cache_tag. As of Python 3.3, sys.implementation.cache_tag is used by importlib to support PEP 3147 compliance. Any Python implementation that uses importlib for its built-in import system may use cache_tag to control the caching behavior for modules.
SimpleNamespace
The implementation of sys.implementation also introduces a new type to Python: types.SimpleNamespace. In contrast to a mapping-based namespace, like dict, SimpleNamespace is attribute-based, like object. However, unlike object, SimpleNamespace instances are writable. This means that you can add, remove, and modify the namespace through normal attribute access.
参见
PEP 421 - 添加 sys.implementation
PEP 由 Eric Snow 撰写并实现
使用 importlib 作为导入的实现
bpo-2377 - Replace import w/ importlib.import bpo-13959 - Re-implement parts of imp in pure Python bpo-14605 - Make import machinery explicit bpo-14646 - Require loaders set loader and package
The import() function is now powered by importlib.import(). This work leads to the completion of “phase 2” of PEP 302. There are multiple benefits to this change. First, it has allowed for more of the machinery powering import to be exposed instead of being implicit and hidden within the C code. It also provides a single implementation for all Python VMs supporting Python 3.3 to use, helping to end any VM-specific deviations in import semantics. And finally it eases the maintenance of import, allowing for future growth to occur.
For the common user, there should be no visible change in semantics. For those whose code currently manipulates import or calls import programmatically, the code changes that might possibly be required are covered in the Porting Python code section of this document.
新的API
One of the large benefits of this work is the exposure of what goes into making the import statement work. That means the various importers that were once implicit are now fully exposed as part of the importlib package.
The abstract base classes defined in importlib.abc have been expanded to properly delineate between meta path finders and path entry finders by introducing importlib.abc.MetaPathFinder and importlib.abc.PathEntryFinder, respectively. The old ABC of importlib.abc.Finder is now only provided for backwards-compatibility and does not enforce any method requirements.
In terms of finders, importlib.machinery.FileFinder exposes the mechanism used to search for source and bytecode files of a module. Previously this class was an implicit member of sys.path_hooks.
For loaders, the new abstract base class importlib.abc.FileLoader helps write a loader that uses the file system as the storage mechanism for a module’s code. The loader for source files (importlib.machinery.SourceFileLoader), sourceless bytecode files (importlib.machinery.SourcelessFileLoader), and extension modules (importlib.machinery.ExtensionFileLoader) are now available for direct use.
ImportError now has name and path attributes which are set when there is relevant data to provide. The message for failed imports will also provide the full name of the module now instead of just the tail end of the module’s name.
The importlib.invalidate_caches() function will now call the method with the same name on all finders cached in sys.path_importer_cache to help clean up any stored state as necessary.
可见的改变
For potential required changes to code, see the Porting Python code section.
Beyond the expanse of what importlib now exposes, there are other visible changes to import. The biggest is that sys.meta_path and sys.path_hooks now store all of the meta path finders and path entry hooks used by import. Previously the finders were implicit and hidden within the C code of import instead of being directly exposed. This means that one can now easily remove or change the order of the various finders to fit one’s needs.
Another change is that all modules have a __loader__ attribute, storing the loader used to create the module. PEP 302 has been updated to make this attribute mandatory for loaders to implement, so in the future once 3rd-party loaders have been updated people will be able to rely on the existence of the attribute. Until such time, though, import is setting the module post-load.
Loaders are also now expected to set the __package__ attribute from PEP 366. Once again, import itself is already setting this on all loaders from importlib and import itself is setting the attribute post-load.
None is now inserted into sys.path_importer_cache when no finder can be found on sys.path_hooks. Since imp.NullImporter is not directly exposed on sys.path_hooks it could no longer be relied upon to always be available to use as a value representing no finder found.
All other changes relate to semantic changes which should be taken into consideration when updating code for Python 3.3, and thus should be read about in the Porting Python code section of this document.
(由 Brett Cannon 编写的实现)
其他语言特性修改
对Python 语言核心进行的小改动:
- Added support for Unicode name aliases and named sequences. Both unicodedata.lookup() and
'\N{...}'now resolve name aliases, and unicodedata.lookup() resolves named sequences too.
(由 Ezio Melotti 在 bpo-12753 中贡献。)
-
Unicode 数据库更新至 UCD 版本 6.1.0
-
Equality comparisons on range() objects now return a result reflecting the equality of the underlying sequences generated by those range objects. (bpo-13201)
-
The
count(),find(),rfind(),index()andrindex()methods of bytes and bytearray objects now accept an integer between 0 and 255 as their first argument.
(由 Petri Lehtinen 在 bpo-12170 中贡献。)
-
The
rjust(),ljust(), andcenter()methods of bytes and bytearray now accept a bytearray for thefillargument. (Contributed by Petri Lehtinen in bpo-12380.) -
New methods have been added to list and bytearray:
copy()andclear()(bpo-10516). Consequently, MutableSequence now also defines aclear()method (bpo-11388). -
Raw bytes literals can now be written
rb"..."as well asbr"...".
(由 Antoine Pitrou 在 bpo-13748 中贡献。)
- dict.setdefault() now does only one lookup for the given key, making it atomic when used with built-in types.
(由 Filip Gruszczyński 在 bpo-13521 中贡献。)
- The error messages produced when a function call does not match the function signature have been significantly improved.
(由 Benjamin Peterson 贡献。)
A Finer-Grained Import Lock
Previous versions of CPython have always relied on a global import lock. This led to unexpected annoyances, such as deadlocks when importing a module would trigger code execution in a different thread as a side-effect. Clumsy workarounds were sometimes employed, such as the PyImport_ImportModuleNoBlock() C API function.
In Python 3.3, importing a module takes a per-module lock. This correctly serializes importation of a given module from multiple threads (preventing the exposure of incompletely initialized modules), while eliminating the aforementioned annoyances.
(由 Antoine Pitrou 在 bpo-9260 中贡献。)
Builtin functions and types
-
open() gets a new opener parameter: the underlying file descriptor for the file object is then obtained by calling opener with (file , flags). It can be used to use custom flags like os.O_CLOEXEC for example. The
'x'mode was added: open for exclusive creation, failing if the file already exists. -
print(): added the flush keyword argument. If the flush keyword argument is true, the stream is forcibly flushed.
-
hash(): hash randomization is enabled by default, see object.hash() and PYTHONHASHSEED.
-
The str type gets a new casefold() method: return a casefolded copy of the string, casefolded strings may be used for caseless matching. For example,
'ß'.casefold()returns'ss'. -
The sequence documentation has been substantially rewritten to better explain the binary/text sequence distinction and to provide specific documentation sections for the individual builtin sequence types (bpo-4966).
新增模块
faulthandler
This new debug module faulthandler contains functions to dump Python tracebacks explicitly, on a fault (a crash like a segmentation fault), after a timeout, or on a user signal. Call faulthandler.enable() to install fault handlers for the SIGSEGV, SIGFPE, SIGABRT, SIGBUS, and SIGILL signals. You can also enable them at startup by setting the PYTHONFAULTHANDLER environment variable or by using -X faulthandler command line option.
Linux 上的段错误示例:
$ python -q -X faulthandler
>>> import ctypes
>>> ctypes.string_at(0)
Fatal Python error: Segmentation fault
Current thread 0x00007fb899f39700:
File "/home/python/cpython/Lib/ctypes/__init__.py", line 486 in string_at
File "<stdin>", line 1 in <module>
Segmentation fault
ipaddress
The new ipaddress module provides tools for creating and manipulating objects representing IPv4 and IPv6 addresses, networks and interfaces (i.e. an IP address associated with a specific IP subnet).
(由 Google 和 Peter Moody 在 bpo-3144 中贡献。)
lzma
The newly added lzma module provides data compression and decompression using the LZMA algorithm, including support for the .xz and .lzma file formats.
(由 Nadeem Vawda 和 Per Øyvind Karlsen 在 bpo-6715 中贡献。)
改进的模块
abc
Improved support for abstract base classes containing descriptors composed with abstract methods. The recommended approach to declaring abstract descriptors is now to provide __isabstractmethod__ as a dynamically updated property. The built-in descriptors have been updated accordingly.
-
abc.abstractproperty has been deprecated, use property with abc.abstractmethod() instead.
-
abc.abstractclassmethod has been deprecated, use classmethod with abc.abstractmethod() instead.
-
abc.abstractstaticmethod has been deprecated, use staticmethod with abc.abstractmethod() instead.
(由 Pablo Galindo 在 bpo-11610 中贡献。)
abc.ABCMeta.register() now returns the registered subclass, which means it can now be used as a class decorator (bpo-10868).
array
The array module supports the long long type using q and Q type codes.
(由 Oren Tirosh 和 Hirokazu Yamamoto 在 bpo-1172711 中贡献。)
base64
ASCII-only Unicode strings are now accepted by the decoding functions of the base64 modern interface. For example, base64.b64decode('YWJj') returns b'abc'. (Contributed by Catalin Iacob in bpo-13641.)
binascii
In addition to the binary objects they normally accept, the a2b_ functions now all also accept ASCII-only strings as input. (Contributed by Antoine Pitrou in bpo-13637.)
bz2
bz2 模块已被重新编写。 在此过程中,添加了一些新的特征:
-
新的 bz2.open() 函数:以二进制或文本模式打开 bzip2 压缩文件。
-
bz2.BZ2File 现在可以读写任意文件型对象,具体方式是通过其构造器的 fileobj 参数。
(由 Nadeem Vawda 在 bpo-5863 中贡献。)
- bz2.BZ2File and bz2.decompress() can now decompress multi-stream inputs (such as those produced by the pbzip2 tool). bz2.BZ2File can now also be used to create this type of file, using the
'a'(append) mode.
(由 Nir Aides 在 bpo-1625 中贡献。)
- bz2.BZ2File now implements all of the io.BufferedIOBase API, except for the
detach()andtruncate()methods.
编码器
The mbcs codec has been rewritten to handle correctly replace and ignore error handlers on all Windows versions. The mbcs codec now supports all error handlers, instead of only replace to encode and ignore to decode.
A new Windows-only codec has been added: cp65001 (bpo-13216). It is the Windows code page 65001 (Windows UTF-8, CP_UTF8). For example, it is used by sys.stdout if the console output code page is set to cp65001 (e.g., using chcp 65001 command).
Multibyte CJK decoders now resynchronize faster. They only ignore the first byte of an invalid byte sequence. For example, b'\xff\n'.decode('gb2312', 'replace') now returns a \n after the replacement character.
Incremental CJK codec encoders are no longer reset at each call to their encode() methods. For example:
>>> import codecs
>>> encoder = codecs.getincrementalencoder('hz')('strict')
>>> b''.join(encoder.encode(x) for x in '\u52ff\u65bd\u65bc\u4eba\u3002 Bye.')
b'~{NpJ)l6HK!#~} Bye.'
This example gives b'~{Np~}~{J)~}~{l6~}~{HK~}~{!#~} Bye.' with older Python versions.
unicode_internal 编解码器已被弃用。
collections
Addition of a new ChainMap class to allow treating a number of mappings as a single unit. (Written by Raymond Hettinger for bpo-11089, made public in bpo-11297.)
The abstract base classes have been moved in a new collections.abc module, to better differentiate between the abstract and the concrete collections classes. Aliases for ABCs are still present in the collections module to preserve existing imports. (bpo-11085)
The Counter class now supports the unary + and - operators, as well as the in-place operators +=, -=, |=, and &=. (Contributed by Raymond Hettinger in bpo-13121.)
contextlib
ExitStack now provides a solid foundation for programmatic manipulation of context managers and similar cleanup functionality. Unlike the previous contextlib.nested API (which was deprecated and removed), the new API is designed to work correctly regardless of whether context managers acquire their resources in their __init__ method (for example, file objects) or in their __enter__ method (for example, synchronisation objects from the threading module).
crypt
Addition of salt and modular crypt format (hashing method) and the mksalt() function to the crypt module.
curses
-
If the curses module is linked to the ncursesw library, use Unicode functions when Unicode strings or characters are passed (e.g.
waddwstr()), and bytes functions otherwise (e.g.waddstr()). -
Use the locale encoding instead of
utf-8to encode Unicode strings. -
curses.window添加了新的 curses.window.encoding 属性。 -
curses.window类有一个新的 get_wch() 方法用来获取一个宽字符。 -
curses 模块有一个新的 unget_wch() 函数用来推入一个宽字符以便下一个 get_wch() 将返回它。
(由 Iñigo Serna 在 bpo-6755 中贡献。)
datetime
-
Equality comparisons between naive and aware datetime instances now return False instead of raising TypeError (bpo-15006).
-
New datetime.datetime.timestamp() method: Return POSIX timestamp corresponding to the datetime instance.
-
The datetime.datetime.strftime() method supports formatting years older than 1000.
-
The datetime.datetime.astimezone() method can now be called without arguments to convert datetime instance to the system timezone.
(本文超出站点单文档体积上限,已按小节截断)
