首页 ¦ 归档

Python3.6新特性官方文档中文版

原文:Python 3.6新特性简介

Python 3.6新特性简介

版本: 3.6.0
日期: December 15, 2016
编辑: Elvis Pranskevichus
<elvis@magic.io>, Yury Selivanov
<yury@magic.io>

这篇文章介绍了与3.5相比, Python 3.6中多出的新特性。

另请参阅

PEP 494 - Python 3.6 发布时间表

摘要 - 发布亮点

新的语法特性:

  • PEP 498, 格式化字符串字面量
  • PEP 515, 数字字面量中的下划线
  • PEP 526, 变量注解中的语法
  • PEP 525, 异步生成器
  • PEP 520: 异步解析式

新的库模块

  • secrets: PEP 506 - 在标准库中添加了Secrets模块

CPython实现的改进:

  • 重新实现了字典(dict)类型,以便能像PyPy的字典类型一样使用更紧凑的表达方式。与Python 3.5相比,这使字典的内存用量减少了20%到25%。
  • 用新协定优化了类的自定义建立。
  • 类属性定义顺序(class attribute definition order)现在被保留了
  • **kwargs内的元素顺序现在对应于将关键字(保留字)参数传递给函数的顺序
  • 新增了对DTrace和SystemTap probing的支持。
  • 新PYTHONMALLOC环境变量现在可用于调试解释器内存分配与访问错误。

标准库的重大改进:

  • asyncio模块开发了新功能、显著的可用性、性能优化,以及大量的错误修复。 从Python 3.6开始,asyncio模块不再是临时的了,其API也进入了稳定状态。
  • 实现了用于支持类路径对象(path-like objects)的新文件系统路径协议。 所有在路径(path)上使用的标准库函数都已更新,以便适应于新协议。
  • datetime模块已获得对本地时间消歧(Local Time Disambiguation)的支持。
  • 针对typing模块的一些改进,使其不再是临时模块。
  • tracemalloc模块已重大改进,现用于为ResourceWarning提供更好的输出,并为内存分配错误提供更好的诊断。 欲知详情,请参阅PYTHONMALLOC部分。

安全相关的改进:

  • secrets模块被用于简化那些适用于管理密文的密码学安全伪随机数生成器(cryptographically strong pseudo-random numbers)的生成过程,如认证、token等。
  • 在Linux上,现将os.urandom()改成了阻塞模式,直到系统的urandom的熵池(entropy pool)的初始化具有更高的安全性。 解释请参见PEP 524
  • hashlibssl模块现已支持OpenSSL 1.1.0。
  • 改进了ssl模块的默认设置和特性集。
  • 新增了hashlib模块对BLAKE2、SHA-3、SHAKE哈希算法以及scrypt()密钥导出函数的支持。

Windows上的改进:

  • PEP 528与PEP 529,Windows文件系统和控制台的编码已更改为UTF-8。
  • 当用户没有指定版本(通过命令行参数或配置文件)时,py.exe启动器以交互方式使用时,不再以Python 2优先于Python 3。 处理shebang行的方式保持不变 - 此处的“python”依旧指Python 2。
  • python.exe和pythonw.exe已标记为长路径敏感(long-path aware),这意味着260字符路径限制可能不再适用。 有关详细信息,请参阅删除MAX_PATH限制
  • 可以添加._pth文件以强制隔离模式(isolated mode)并完全指定所有搜索路径,以避免注册表查找和环境查找。 有关详细信息,请参阅文档
  • 一个python36.zip文件现可用作一个地标(landmark)以臆指PYTHONHOME。 有关详细信息,请参阅文档

新特性

PEP 498: 格式化字符串

PEP 498引入了一种新的字符串:_f-strings_, 或者格式化字符串

格式化字符串带'f'前缀,类似于str.format()接受的格式字符串。它们包含了由花括号括起来的替换字段。替换字段是表达式,它们会在运行时计算,然后使用format()协议进行格式化:

    >>> name = "Fred"
    >>> f"He said his name is {name}."
    'He said his name is Fred.'
    >>> width = 10
    >>> precision = 4
    >>> value = decimal.Decimal("12.34567")
    >>> f"result: {value:{width}.{precision}}"  # nested fields
    'result:      12.35'

又见

PEP 498 - 字符串插值。

PEP由Eric V. Smith编写和实现。

特性文档

PEP 526: 变量注释语法

PEP 484引入了函数参数的类型注释的标准,又名类型提示。这个PEP添加了用来注释变量(包括类变量和实例变量)类型的语法:

    primes: List[int] = []

    captain: str  # Note: no initial value!

    class Starship:
        stats: Dict[str, int] = {}

正如函数注释,Python解释器不附加任何特殊意义到变量注释上,只是将它们存储在一个类或者模块的__annotations__属性中。

与静态类型语言中的变量声明相比,注释语法的目的在于提供一种简单的方式,通过抽象语法树和__annotations__属性,来为第三方工具和库指定结构化类型元数据。

又见

PEP 526 - 变量注释语法。

PEP由Ryan Gonzalez, Philip House, Ivan Levkivskyi, Lisa Roach, 和Guido van Rossum编写。由Ivan Levkivskyi实现。

使用或将要使用这个新语法的工具:mypy, pytype, PyCharm等等。

PEP 515: 数值文字中的下划线

PEP 515添加了在数值文字中使用下划线的能力,以提高可读性。例如:

    >>> 1_000_000_000_000_000
    1000000000000000
    >>> 0x_FF_FF_FF_FF
    4294967295

数字之间和任何基本符号之后允许单个下划线。不允许前置、后置或者多个连续的下划线。

字符串格式化语言现在还支持'_'选项,该选项用来通知对浮点表示类型和整型表示类型'd',会把下划线当成千位分隔符使用。对于整型表示类型'b', 'o', 'x', 和'X', 下划线将会被插入到每4个数字之间:

    >>> '{:_}'.format(1000000)
    '1_000_000'
    >>> '{:_x}'.format(0xFFFFFFFF)
    'ffff_ffff'

又见

PEP 515 - 数值文字中的下划线

PEP由Georg Brandl和Serhiy Storchaka编写。

PEP 525: 异步生成器

PEP 492 引入支持原生协程和async /await的语法到Python 3.5。 在Python 3.5实现里的一个值得注意的 局限性就在于它不可能使用await和`yield'在同一个函数体中。 而在Python 3.6中,这个限制 已解除,这使得定义_异步生成器_成为可能:

    async def ticker(delay, to):
        """Yield numbers from 0 to *to* every *delay* seconds."""
        for i in range(to):
            yield i
            await asyncio.sleep(delay)

新的语法允许更快更简洁的代码。

参见 PEP 525 - 异步生成器

由Yury Selivanov撰写并实现的PEP。

PEP 530: 异步解析式

PEP 530 添加了对async for在list、set、dict解析式以及generator表达式中的使用支持:

    result = [i async for i in aiter() if i % 2]

此外,所有解析式都支持“await”表达式:

    result = [await fun() for fun in funcs if await condition()]

参见 PEP 530 - 异步解析式

由Yury Selivanov撰写并实现的PEP。

PEP 487: 用于建立类的更简单的自定义

现在可以在不使用元类的情况下自定义子类。每当创建一个新的子类时,新的__init_subclass__类方法将在基类上被调用,:

    class PluginBase:
        subclasses = []

        def __init_subclass__(cls, **kwargs):
            super().__init_subclass__(**kwargs)
            cls.subclasses.append(cls)

    class Plugin1(PluginBase):
        pass

    class Plugin2(PluginBase):
        pass

为了允许零参数 super()_init_subclass __()实现中被正确的调用并工作,自定义元类必须确保 新的__classcell__命名空间输入传递到type .__ new__ (如创建类 对象)

参见

PEP 487 - 用于建立类的更简单的自定义

由Martin Teichmann撰写并实现的PEP。

功能文档

PEP 487: 描述符协议增强

PEP 487 扩展描述符协议必须包括新的可选的__set_name __()方法。 每当定义一个新类时,新方法将会调用定义中所有的描述符,并给它们提供定义类的引用,以及类命名空间中给予描述符的名字。 换句话说,描述符的实例现在可以获知所有者类的属性名:

    class IntField:
        def __get__(self, instance, owner):
            return instance.__dict__[self.name]

        def __set__(self, instance, value):
            if not isinstance(value, int):
                raise ValueError(f'expecting integer in {self.name}')
            instance.__dict__[self.name] = value

        # this is the new initializer:
        def __set_name__(self, owner, name):
            self.name = name

    class Model:
        int_field = IntField()

参见

PEP 487 - 用于建立类的更简单的自定义

由Yury Selivanov撰写并实现的PEP。

功能文档

PEP 519: 添加文件系统路径协议

文件系统路径过去被表示为strbytes对象。这会导致那些编写操作文件系统路径代码的人,假定这些对象只能是这两种类型之一(一个代表着文件描述符的int对象将不被计入即它不是一个文件路径)。 不幸的是,这种假设局限了文件系统路径表示代方法,如已经存在的pathlib,同时也包括python的一些标准库。 为了解决这种情况,定义了一个由os.PathLike表示的新接口。通过实现__fspath__()方法,一个对象表示一个路径,然后,可以将文件系统路径表示为一个较低等级的str或者bytes对象。这意味着,如果一个对象实现os.PathLike或者是strbytes,该对象被认为是path- like,它代表一个文件系统路径。你可以使用os.fspath(),os.fsdecode()os.fsencode()显式获取str以及/或bytes来表示一个path-like对象。 内建函数open()已经更新,可以接受os.PathLike对象,以及在osos.path模块中的所有函数,以及标准库中的大多数其他函数和类。类os.DirEntry以及pathlib中相关的类也已经可以实现os.PathLike。 希望对操作文件系统路径基本功能的更新能够让第三方代码在不改变任何代码,或者至少是非常少的代码(例如,在操作path-like对象之前,在代码的开头调用os.fspath())的情况下,能够隐含地支持所有path-like objects对象。 下面举一些例子说明新接口是如何让预先存在的代码简单透明地使用pathlib.Path:

    >>> import pathlib
    >>> with open(pathlib.Path("README")) as f:
    ...     contents = f.read()
    ...
    >>> import os.path
    >>> os.path.splitext(pathlib.Path("some_file.txt"))
    ('some_file', '.txt')
    >>> os.path.join("/a/b", pathlib.Path("c"))
    '/a/b/c'
    >>> import os
    >>> os.fspath(pathlib.Path("some_file.txt"))
    'some_file.txt'

(由Brett Cannon, Ethan Furman, Dusty Phillips, and Jelle Zijlstra实现)

参见

PEP 519 - 添加文件系统路径协议

PEP 由Brett Cannon 和 Koos Zevenhoven撰写.

PEP 495: 本地时间消歧

世界上大多数地方,都曾经出现也将出现多次的时间回调。在这种时候,引入时间间隔用以表示本地时钟在同一天中出现两次相同的时间的情况,在这些情况下,本地时钟显示的时间(或存在在python datetime中的实例)不足及时表示特定的时刻。 为了区分本地时间相同的两个时刻,PEP 495 在类 datetime.datetime`datetime.tim e` 的实例中增加了新的fold属性:

    >>> u0 = datetime(2016, 11, 6, 4, tzinfo=timezone.utc)
    >>> for i in range(4):
    ...     u = u0 + i*HOUR
    ...     t = u.astimezone(Eastern)
    ...     print(u.time(), 'UTC =', t.time(), t.tzname(), t.fold)
    ...
    04:00:00 UTC = 00:00:00 EDT 0
    05:00:00 UTC = 01:00:00 EDT 0
    06:00:00 UTC = 01:00:00 EST 1
    07:00:00 UTC = 02:00:00 EST 0

属性 fold 的值除了表示不明确情况下的第二(时间顺序)时刻之外,其他所有实例的值都为 0。 See also

PEP 495 - 本地时间消歧

PEP 由 Alexander Belopolsky 和 Tim Peters撰写, 由Alexander Belopolsky实现.

PEP 529: 更改windows下文件系统编码格式为UTF-8

使用str (Unicode) 表示文件系统路径比bytes能获得更好的效果。尽管如此,在某些情况下bytes也足以胜任并且也是正确的。

在3.6之前,使用bytes路径可能导致数据丢失。改进后, windows下现在支持使用bytes表示路径,这些bytes将以sys.getfilesy stemencoding()的方式编码,默认编码格式为'utf-8'

不使用str方式表示路径的应用程序应当使用os.fsencode()os.fsdecode() 以确保他们的bytes被正确编码。要回复到之前的状态, 设置 PYTHONLEGACYWINDOWSFSENCODING 或者调用 sys._enablelegacywindowsfsencoding()

查看 PEP 529以获取更多信息并讨论可能需要变更的代码。

PEP 528: 更改windows控制台编码为UTF-8

windows下的默认控制台现在支持所有的Unicode字符并可以正确读取Python代码中的str对象。 sys.stdin, sys.stdout 以及 sys.stderr 现在的默认使用utf-8编码。

这一变化仅适用于使用交互控制台之时,而非重定向文件或者管道。如果要使用之前的交互控制台, 需设置 PYTHONLEGACYWINDOWSIOENCODING

另请参阅

PEP 528 - 修改windows控制台编码为UTF-8

PEP 由Steve Dower编写和实现。

PEP 520: 保存类属性定义顺序

类的定义体中的属性有一个自然顺序:即源码中属性名出现的顺序。 这个顺序现在保存在新的类__dict__ 的属性中.

同样, 有效的缺省类和执行空间 (从type.prepare()返回)是一个保存插入顺序的映射。

另请参阅

PEP 520 - 保存类属性定义顺序

该PEP由Eric Snow编写和实现。

PEP 468: 保存关键字参数顺序

函数声明中的**kwargs 的顺序现在被保证是插入顺序的映射。

另请参阅

PEP 468 - 保存关键字参数顺序

该PEP由Eric Snow编写和实现。

新的 字典dict类型的实现

字典dict类型现在使用 PyPy首创的 "紧凑" 表达方式。 新字典dict() 的内存占用比Python3.5中减少20%到25%。

新的实现中保存顺序的功能被认为是不可过于依赖的(未来也许会改变,不过在将所有当前和未来的Python实现的语言规范转换为保证顺序的语法之前的几个版本中,新的dict有望被实现的; 这也能帮助保证对那些仍旧是随机迭代顺序的旧版本的向后兼容,比如Python 3.5)。

(由INADA Naoki在issue 27350提供。 想法 最初由Raymond Hettinger提出.)

PEP 523:添加一个frame解析API到CPython

虽然Python提供了自定义代码执行方式的广泛支持,但是还有一个它没这样做的地方是frame对象的解析。如果你想要通过某些方式在Python中拦截frame解析,那么除了直接对定义的函数操作函数指针之外,真的没有什么其他方式。

PEP 523改变了这个处境,它提供了一个API,让frame解析在C层次上可插拔。这将允许诸如调试器或者JIT这样的工具在Python代码开始执行之前拦截frame解析。这使得python代码的可替换解析实现、跟踪frame解析等地使用成为可能。

这个API并不是受限的C API的一部分,并且被标为私有,表示期望限制这个API的使用,并且只能应用在非常选定的低层次用例上。这个API的语义将在必要的时候随着Python改动。

又见

PEP 523 - 添加一个frame解析API到CPython

PEP由Brett Cannon和Dino Viehland编写

PYTHONMALLOC环境变量

新的PYTHONMALLOC环境变量允许设置Python内存分配器和安装调试钩子。

现在有可能在发布模式下使用PYTHONMALLOC=debug编译的Python中,在Python内存分配器上安装调试钩子。调试钩子的效果:

  • 新分配内存由字节0xCB填充
  • 被释放内存由字节0xDB填充
  • 检测Python内存分配器API的违规。例如,在由PyMem_Malloc()分配的内存块上调用PyObject_Free()
  • 检测缓存开始位置之前的写入 (缓存下溢)
  • 检测缓存结束位置之后的写入 (缓存上溢)
  • 当调用了PYMEM_DOMAIN_OBJ (例如,PyObject_Malloc())和PYMEM_DOMAIN_MEM (例如,PyMem_Malloc())域的分配器函数时,检测持有GIL

检测是否持有GIL也是Python 3.6的一个新特性。

PyMem_SetupDebugHooks()函数,了解更多关于Python内存分配器上的调试钩子信息。

现在也有可能使用PYTHONMALLOC=malloc,从而强制所有Python内存分配使用C库的malloc()分配器。这在以发布模式编译的Python上,使用诸如Valgrind这样的外部内存调试器是有帮助的。

对于错误,Python内存分配器上的调试钩子现在使用tracemalloc模块来获取分配内存块的地址的回溯信息。

使用python3.6 -X tracemalloc=5 (存储5个帧到回溯中)时,在缓存上溢时的致命错误的例子:

    Debug memory block at address p=0x7fbcd41666f8: API 'o'
        4 bytes originally requested
        The 7 pad bytes at p-7 are FORBIDDENBYTE, as expected.
        The 8 pad bytes at tail=0x7fbcd41666fc are not all FORBIDDENBYTE (0xfb):
            at tail+0: 0x02 *** OUCH
            at tail+1: 0xfb
            at tail+2: 0xfb
            at tail+3: 0xfb
            at tail+4: 0xfb
            at tail+5: 0xfb
            at tail+6: 0xfb
            at tail+7: 0xfb
        The block was made by call #1233329 to debug malloc/realloc.
        Data at p: 1a 2b 30 00

    Memory block allocated at (most recent call first):
      File "test/test_bytes.py", line 323
      File "unittest/case.py", line 600
      File "unittest/case.py", line 648
      File "unittest/suite.py", line 122
      File "unittest/suite.py", line 84

    Fatal Python error: bad trailing pad byte

    Current thread 0x00007fbcdbd32700 (most recent call first):
      File "test/test_bytes.py", line 323 in test_hex
      File "unittest/case.py", line 600 in run
      File "unittest/case.py", line 648 in __call__
      File "unittest/suite.py", line 122 in run
      File "unittest/suite.py", line 84 in __call__
      File "unittest/suite.py", line 122 in run
      File "unittest/suite.py", line 84 in __call__
      ...

(由Victor Stinner于issue 26516issue 26564贡献。)

DTrace和SystemTap探测支持

Python现在可以使用--with-dtrace来构建,它为解释器中的以下事件启用了静态标志器:

  • 函数调用/返回
  • 垃圾回收开始/结束
  • 执行代码行。

这可以被用来检测生产中运行的解释器,而无需重新编译指定调试构建,或者提供应用特有的配置/调试代码。

详情请见用DTrace和SystemTap检测CPython

在Linux和macOS上测试了当前实现。未来可能会添加额外的标志器。

(由Łukasz Langa在issue 21590中贡献,基于Cea Avión, David Malcolm, 和Nikhil Benesch提供的补丁)

其他语言方面的变化

我们还对 Python 语言的核心做了一些小的改变:

  • 现在在同一作用域内的 globalnonlocal 语句必须在受其影响的命名使用前显式出现。在先前版本中会发出 语法警告
  • 现在能以将 魔术方法 设置为 None 的方式来表示相应的操作不可用。 例如,如果将一个类的 __iter__() 设置为None,则该类不可迭代。(由 Andrew Barnert 和 Ivan Levkivskyi 在 issue 25958 中贡献。)
  • 在 traceback 中大量重复出现的 traceback lines 将会被略写成 "[前一行已经重复出现 {count} 次了]" (以 traceback 为例。). (由 Emanuel Barry 在 issue 26823 中贡献。)
  • 现在模块导入在找不到模块时引发新的异常 ModuleNotFoundErrorImportError 的子类)。 当前检测 ImportError 的代码(try-except中)仍然可以工作。(由 Eric Snow 在 issue 15767 中贡献。)
  • 在类创建时,被元类调用的依赖无参数的 super() 的类方法时会正确工作。(由 Martin Teichmann 在 issue 23722中贡献。)

新增模块

secrets

新增模块 secrets 的主要目的是:提供一个 显式可靠的方式来产生适合于管理诸如账户认证,令牌之类的保密信息的加密的强伪随机值。

警告

注意在 random 模块中的随机数生成器 不该 用于安全目的。Python 3.6 及以上版本请使用 secrets 而 Python 3.5 及更早的版本请使用 os.urandom()

又见

PEP 506 - 向标准库添加 Secrets 模块

PEP 由 Steven D'Aprano 编写及实现。

改进模块

array

耗尽的迭代器array.array现在将会保持被耗尽,即使被迭代的数组被拓展了。这与其他可变序列的行为保持了一致性。

由Serhiy Storchaka在issue 26492中贡献

ast

添加了新的ast.Constant的AST节点。它可以被外部的AST优化器出于永久聚合(constant foldind)。

由Victor Stinner在issue 26146中贡献

asyncio

始于Python 3.6,asyncio模块将不再是临时的了,并且它的API被认为是稳定的。

从Python 3.5开始,在asyncio模块中值得注意的变化(由于临时的状态,所有的修改都应用到了3.5.x):

  • get_event_loop()函数已经被改变为,当从协同程序中调用和被回调调用时,总是返回当前正在运行的循环。(由 Yury Selivanovgong贡献于issue 28613。)
  • ensure_future()函数和所有使用其的函数,比如loop.run_until_complete(),现在接收所有种类的awaitable objects。(由 Yury Selivanov贡献)。
  • 新的run_coroutine_threadsafe()函数去从其他线程中提交协同程序到事件循环中。(由Vincent Michel贡献)
  • 新的Transport.is_closing()方法去检查是否传输是关闭的或被关闭了(由Yury Selivanov贡献)。
  • loop.creat_server()现在可以以列表接收主机了。(由Yann Sionneaugong贡献)
  • 新的loop.creat_future()方法去创建一个Future对象。这允许了替代事件循环的实现,比如uvloop,去提供了一种更快的asyncio.Future的实现。(由Yury Selivanov在issue 27041中贡献)
  • 新的loop.get_exception_handler()方法去得到一个当时的异常的句柄。(由Yury Selivanov在issue 27040中贡献)
  • 新的StreamReader.readuntil()方法从流中读取数据读取数据直到出现分隔符字符序列。(由Mark Korenberg贡献)
  • StreamReader.readexactly()的表现被提升了。(由Mark Korenberg在issue 28370中贡献)
  • loop.getaddrinfo()方法被优化了,避免了如果地址问题已经解决,去调用系统函数getaddrinfo。(由A. Jesse Jiryu Davis贡献)
  • loop.stop()方法已经被更改,以便在当前迭代后立即停止循环。任何新的,作为最后一次迭代的结果的预定的回调将会被丢弃。(由Guido van Rossum在issue 25593中贡献)
  • Future.set_exception在通过了一个StopIteration实例的异常后,将会引发TypeError。(由Chris Angelico在issue 26221贡献)
  • 新的loop.connect_accepted_socket()方法被服务器用来接收asyncio外部的连接,但是使用asyncio去处理。(由Jim Fulton在issue 27392中贡献)
  • TCP_NODELAY标志位现在被默认设置为TCP传输。(由Yury Selivanov在issue 27456中贡献)
  • 新的loop.shutdown_asyncgens()在关闭循环之前恰当的关闭挂起的异步生成器。(由 Yury Selivanov在issue 28003中贡献)
  • FutureTask类现在有一个已优化的C语言的实现,使得asyncio编码速度提高了30%。(由Yury Selivanov和INADA Naoki在issue 26081issue 28544中贡献)

binascii

b2a_base64()功能现在接收现在接收一个可选_newline_的关键词参数去控制是否新的一行的字符被加到返回值中。(由Victor Stinnergong贡献于issue25357。)

cmath

新增了方法 cmath.tau 来表示(τ) 常量. (由Lisa Roach在issue 12345中贡献, 详情请查看 **PEP 628** .)

新增的常量还有: cmath.infcmath.nan 来对应 math.infmath.nan, 另外还有 cmath.infjcmath.nanj 来匹配复数表达式的格式化. (由Mark Dickinson在issue 23229中贡献.)

collections

新的Collection 抽象基类已经增加到可表示大小的迭代器类里面 (由Ivan Levkivskyi贡献, 文档由Neil Girdhar在issue 27598中贡献.)

新的Reversible 有迭代器类的抽象基类 __reversed__() 方法. (由Ivan Levkivskyi在issue 25987中贡献.)

新的 AsyncGenerator ,是一种异步生成器类的抽象基类. (Contributed by Yury Selivanov in issue 28720.)

这个namedtuple() 函数现在接受一个可选的关键字参数 module, 它指定用于__module__返回的命名元组类的属性. (由Raymond Hettinger 在issue 17941中贡献.

namedtuple()的_verbose_ 和 rename 参数是强制关键字参数. (由Raymond Hettinger 在issue 25628中贡献.)

递归方法collections.deque 实例现在可使用pickle持久化存储. (由Serhiy Storchaka在issue 26482中贡献.)

concurrent.futures¶

ThreadPoolExecutor 类的构造函数现在接受一个可选的 thread_name_prefix 参数,使自定义线程池中的线程名字成为可能 (由Gregory P. Smith 贡献在issue 27664.)

contextlib¶

contextlib.AbstractContextManager 类已经成为上下文管理器中的一个抽象基类 。它提供了一个合理的默认返回selfenter()方法,和一个 exit()抽象方法. 一个匹配的类`typing.Context Manager`.被添加到 typing。 (由 Brett Cannon 贡献在issue 25609.)

datetime

The datetime and time classes have the new fold attribute used to disambiguate local time when necessary. Many functions in the datetime have been updated to support local time disambiguation. See Local Time Disambiguation section for more information. (Contributed by Alexander Belopolsky in issue 24773.)

The datetime.strftime() and `date.strftime( )` methods now support ISO 8601 date directives %G, %u and %V. (Contributed by Ashley Anderson in issue 12006.)

The [datetime.isoformat()](https://docs.python.org/3.6/library/datetime.html

datetime.datetime.isoformat "datetime.datetime.isoformat" ) function now

accepts an optional timespec argument that specifies the number of additional components of the time value to include. (Contributed by Alessandro Cucci and Alexander Belopolsky in issue 19475.)

The datetime.combine() now accepts an optional tzinfo argument. (Contributed by Alexander Belopolsky in issue 27661.)

decimal

New Decimal.as_integer_ratio() method that returns a pair (n, d) of integers that represent the given Decimal instance as a fraction, in lowest terms and with a positive denominator:

    >>> Decimal('-3.14').as_integer_ratio()
    (-157, 50)

(Contributed by Stefan Krah amd Mark Dickinson in issue 25928.)

distutils

The default_format attribute has been removed from distutils.command.sdist.sdist and the formats attribute defaults to ['gztar']. Although not anticipated, any code relying on the presence of default_format may need to be adapted. See issue 27819 for more details.

email

The new email API, enabled via the policy keyword to various constructors, is no longer provisional. The email documentation has been reorganized and rewritten to focus on the new API, while retaining the old documentation for the legacy API. (Contributed by R. David Murray in issue 24277.)

The email.mime classes now all accept an optional policy keyword. (Contributed by Berker Peksag in issue 27331.)

The DecodedGenerator now supports the policy keyword.

There is a new policy attribute, message_factory, that controls what class is used by default when the parser creates new message objects. For the `email.policy.co mpat32` policy this is Message, for the new policies it is EmailMessage. (Contributed by R. David Murray in issue 20476.)

encodings

On Windows, added the 'oem' encoding to use CP_OEMCP, and the 'ansi' alias for the existing 'mbcs' encoding, which uses the CP_ACP code page. (Contributed by Steve Dower in issue 27959.)

enum

Two new enumeration base classes have been added to the enum module: Flag and IntFlags. Both are used to define constants that can be combined using the bitwise operators. (Contributed by Ethan Furman in issue 23591.)

Many standard library modules have been updated to use the IntFlags class for their constants.

The new enum.auto value can be used to assign values to enum members automatically:

    >>> from enum import Enum, auto
    >>> class Color(Enum):
    ...     red = auto()
    ...     blue = auto()
    ...     green = auto()
    ...
    >>> list(Color)
    [<Color.red: 1>, <Color.blue: 2>, <Color.green: 3>]

faulthandler

在Windows平台, faulthandler模块安装了一个指示Windows异常的句柄 : 详情可见于 faulthandler.enable(). (由 Victor Stinner 在 issue 23848中贡献.)

fileinput

hook_encoded() 模块现在可支持errors参数. (由 Joseph Hackman 在 issue 25788贡献.)

hashlib

hashlib 支持 OpenSSL 1.1.0。 推荐使用的最低版本为1.0.2. (由Christian Heimes 在 issue 26470贡献.)

BLAKE2 hash 函数也被收录进这一模块. blake2b()blake2s() 将长期支持BLAKE2的所有特性. (由Christian Heimes in 依据Dmitry Chestnykh 和 Samuel Neves的代码在issue 26798 贡献. 文档由Dmitry Chestnykh撰写.)

新增SHA-3哈希函数 sha3_224(), sha3_256(), sha3_384(), sha3_512(), 与SHAKE 哈希函数 shake_128()shake_256() . (由Christian Heimes 在 issue 16113贡献. Keccak 代码包由Guido Bertoni, Joan Daemen, Michaël Peeters, Gilles Van Assche, and Ronny Van Keer撰写.)

基于密码的密钥导出函数 scrypt() 可使用 OpenSSL 1.1.0 或更新版本. (由Christian Heimes 在 issue 27928中贡献.)

http.client

HTTPConnection.request() and endheaders() 将全部支持分块编码请求体. (由Demian Brecht and Rolf Krahl 在 issue 12319中贡献.)

idlelib and IDLE

对idle包做了现代化的改进与重构,使得IDLE更美观、更好用的同时令编程更易于理解、测试与改进。在IDLE的美化方面,特备针对Linux和Mac用户,我们在大多数对话框上应用了ttk插件。总之,IDLE将不再支持tcl/tk 8.4。现在要求有 tcl/tk 8.5 或 8.6。我们建议在使用时运行最新的版本.

“现代化”包括对idlelib模块的重命名和整合.重命名文件部分大写的名字是与之前版本类似的命名,例如,Tkinter和TkFont对应3.0版本中的Tkinter和tkinter.font 。因此,对idlelib在3.5环境下导入的文件通常不会工作在3.6。至少一个模块的名称需要改变(见idlelib / readme.txt),有时甚至会更多。(名称变更由Al Swiegart 与 Terry Reedy 在 issue 24225中贡献. 大多数idle补丁均会加入这一改进。)

做点补充,最终的结果是,一些idlelib类会更容易使用,将具有更好的API文档与字符串的解释。其他有用的信息会在可用时被及时添加到idlelib。

importlib

当无法找到被导入模块时会跳出一个新的异常提示 ModuleNotFoundError (ImportError的一个子类) . 检测ImportError的代码(try-except)依然会工作。 (由 Eric Snow 在 issue 15767中贡献.)

importlib.util.LazyLoader在打包好的装载器上更名为 `create_ module()` , 去除了 importlib.machinery.BuiltinImporter`importlib.machinery.Ext ensionFileLoader` 不能同 importlib.util.LazyLoader一起使用的限制.

importlib.util.cache_from_source(), importlib.util.source_from_cache(), 和 `importlib.util.spec_from_file _location()` 现在可接受path-like object.

inspect

inspect.signature()函数现在支持报告由编译器为推导式和生成器表达式范围生成的隐式.0参数,就好像它们是名为implicit0的仅位置参数。 (由Jelle Zijlstra在issue 19611中贡献。)

为了减少从Python 2.7和旧版`inspect.getargspec()` API升级时的代码改动,先前记录的对`inspect.getfullargspec()`对弃用已经撤销。虽然这个函数对于单个/源Python 2/3代码库是很方便的,但是更丰富的`inspect.signature()`接口仍然是新代码的推荐方法。(由Nick Coghlan在issue 27172中贡献)

json

json.load()json.loads()现在支持二进制输入。已编码的JSON应该用UTF-8, UTF-16, 或者UTF-32来表示。(由Serhiy Storchaka在issue 17909中贡献。)

logging

已添加新的WatchedFileHandler.reopenIfNeeded()方法来增加检查日志文件是否需要被重新打开的能力。(由Marian Horban在issue 24884中贡献。)

math

已添加tau (τ)常量到mathcmath模块中。(由Lisa Roach在issue 12345中贡献,见**PEP 628**以了解详情。)

multiprocessing

multiprocessing.Manager()返回的Proxy对象现在可以被嵌套。(由Davin Potts在issue 6766中贡献。)

os

PEP 519的摘要,以获取关于osos.path模块现在如何支持类路径(path-like)对象的详情。

scandir()现在支持Windows上的bytes路径。

一个新的close()方法允许显式关闭一个scandir()迭代器。scandir()迭代器现在支持上下文管理器协议。如果一个scandir()迭代器既不是被耗尽,也不是被显式关闭,那么在其析构函数中将会抛出一个ResourceWarning。(由Serhiy Storchaka在issue 25994中贡献。)

在Linux上,os.urandom()现在会阻塞,直到系统的urandom entropy池被初始化,以提高安全性。见**PEP 524**以了解缘由。

Linux的getrandom()系统调用(获取随机字节)现在作为新的os.getrandom()函数公开。(由Victor Stinner贡献,属于**PEP 524**部分)

pathlib

pathlib现在支持类路径(path-like)对象。 (由Brett Cannon在issue 27186中贡献。)

见PEP 519的摘要了解详情。

pdb

Pdb类构造器有一个新的可选_readrc_参数,用来控制是否应该读取.pdbrc文件。

pickle

对象,现在可以使用关键参数 __new__进行持久存储[pickle协议](https://docs.python.org/3.6/library/pickle.html

pickle-protocols)超过已有的协议版本4.

支持这种情况. (由Serhiy Storchaka在issue 24164的贡献。)

pickletools

现在pickletools.dis() 输出的隐含备注是MEMOIZE操作码的索引。 (由Serhiy Storchaka在issue 25382的贡献。)

pydoc

pydoc模块已经学会遵守MANPAGER环境变量。 (由Matthias Klose 在issue 8637的贡献。)

help()pydoc 现在能用指定的元组字段定义的顺序来显示列表,而不是按字母顺序。 (由Raymond Hettinger在issue 24879的贡献。)

random

这个新choices() 函数返回一个指定元素大小的列表,通过可选权重给出它的规模。(由Raymond Hettinger在issue 18844的贡献。)

re

在正则表达式中,增加对 spans 修饰符的支持。 示例: '(?i:p)ython' 匹配 'python''Python', 但不匹配 'PYTHON''(?i)g(?-i:v)r' 匹配 'GvR''gvr', 但不匹配 'GVR'。(由Serhiy Storchaka在 issue 433028 的贡献。)

匹配对象组可通过 __getitem__访问, 它就等价于 group()。因此, 现在mo['name'] 就等价于 mo.group('name')。 (由 Eric Smith 在issue 24454的贡献。)

现在,Match 对象支持 index-like objects 一样的组索引。 (由Jeroen Demeyer and Xiang Zhang 在 issue 27177的贡献。)

readline

增加了 set_auto_history() 启用或停用 自动把输入加到历史列表中。 (由Tyler Crompton 在issue 26870的贡献。)

rlcompleter

现在,除非前缀开始使用下划线,否则私有和特殊属性名称就被忽略。在一些完成的关键字后面添加一个空格或冒号。 (由Serhiy Storchaka 在issue 25011issue 25209的贡献。)

shlex

shlex 已经大大 改进shell的兼容性 ,通过新的 punctuation_chars 参数来控制,哪些字符被作为标点符号。 (由Vinay Sajip 在issue 1521950的贡献。)

site

在一个.pth文件里,当指定路径添加到sys.path 中, 可能你现在要在目录之上指定文件路径 (例如:zip文件)。 (由Wolfgang Langner 在issue 26587的贡献)。

sqlite3

sqlite3.Cursor.lastrowid 现在支持 REPLACE 声明. (贡献者: Alex LordThorsen 于 issue 16864.)

socket

ioctl() 函数现在支持 `SIO_LOOPBACK_FAST_PA TH` 控制代码. (贡献者: Daniel Stokes 于 issue 26536.)

getsockopt() 常量 SO_DOMAIN, SO_PROTOCOL, SO_PEERSEC, 和 SO_PASSSEC 现已被支持. (贡献者:Christian Heimes 于 issue 26907.)

setsockopt() 现在支持 setsockopt(level, optname, None, optlen: int) 形式. (贡献者: Christian Heimes 于 issue 27744.)

socket 模块现在支持地址族 AF_ALG 来和Linux Kernel crypto API连接. 添加了ALG_*, SOL_ALGsendmsg_afalg(). (贡献者: Christian Heimes 于 issue 27744 with support from Victor Stinner.)

socketserver

基于 socketserver 模块, 包括了 http.server, xmlrpc.serverwsgiref.simple_server的Servers 现在支持 context manager protocol. (Contributed by Aviv Palivoda in issue 26404.)

StreamRequestHandler 类的 wfile 属性 现在实现 the `io.Buffered IOBase` 可写接口. 特别地, 调用 write() 现在可以保证完全发送数据. (贡献者: Martin Panter 于 issue 26721.)

ssl

ssl 已支持 OpenSSL 1.1.0. 最低推荐版本号是 1.0.2. (贡献者: Christian Heimes 于 issue 26470.)

3DES 已从默认密码套件default cipher suites中删除 添加了密码套件ChaCha20 Poly1305. (贡献者: Christian Heimes 于 issue 27850issue 27766.)

SSLContext 有更好的默认配置选项和密码. (贡献者: Christian Heimes 于 issue 28043.)

SSL session 可以使用新的 SSLSession 类从一个客户端连接复制到另一个客户端连接. TLS会话恢复可以加速初始握手,减少延迟并提高性能 (贡献者: Christian Heimes 于 issue 19500 ,基于Alex Warhawk的草案.)

新的 get_ciphers() 方法可以用来得到一个 按密码优先级顺序的已启用密码列表.

所有的 constants and flags 已转换为 IntEnumIntFlags. (贡献者 :Christian Heimes 于 issue 28025.)

Server 和 client-side 添加 SSLContext 特定 TLS 协议. (贡献者: Christian Heimes 于 issue 28085.)

statistics

A new harmonic_mean() function has been added. (Contributed by Steven D'Aprano in issue 27181.)

struct

struct now supports IEEE 754 half- precision floats via the 'e' format specifier. (Contributed by Eli Stevens, Mark Dickinson in issue 11734.)

subprocess

subprocess.Popen destructor now emits a ResourceWarning warning if the child process is still running. Use the context manager protocol (with proc: ...) or explicitly call the wait() method to read the exit status of the child process. (Contributed by Victor Stinner in issue 26741.)

The subprocess.Popen constructor and all functions that pass arguments through to it now accept encoding and errors arguments. Specifying either of these will enable text mode for the stdin, stdout and stderr streams. (Contributed by Steve Dower in issue 6135.)

sys

The new getfilesystemencodeerrors() function returns the name of the error mode used to convert between Unicode filenames and bytes filenames. (Contributed by Steve Dower in issue 27781.)

On Windows the return value of the getwindowsversion() function now includes the platform_version field which contains the accurate major version, minor version and build number of the current operating system, rather than the version that is being emulated for the process (Contributed by Steve Dower in issue 27932.)

telnetlib

Telnet is now a context manager (contributed by Stéphane Wirtel in issue 25485).

time

The struct_time attributes tm_gmtoff and tm_zone are now available on all platforms.

timeit

The new Timer.autorange() convenience method has been added to call Timer.timeit() repeatedly so that the total run time is greater or equal to 200 milliseconds. (Contributed by Steven D'Aprano in issue 6422.)

timeit now warns when there is substantial (4x) variance between best and worst times. (Contributed by Serhiy Storchaka in issue 23552.)

tkinter

tkinter.Variable类中添加了方法 trace_add()trace_remove()trace_info()。 它们代替了之前版本中的 trace_variable()trace()trace_vdelete()trace_vinfo()方法,这些方法使用过时的Tcl命令,而在未来版本的Tcl中,这些Tcl命令可能不起作用。(由Serhiy Storchaka在issue 22115 提供)。

traceback

traceback模块和解释器内置的异常展示现在都省略回溯中重复行的长串,如以下例子所示:

    >>> def f(): f()
    ...
    >>> f()
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      File "<stdin>", line 1, in f
      [Previous line repeated 995 more times]
    RecursionError: maximum recursion depth exceeded

(由Emanuel Barry在issue 26823中贡献。)

tracemalloc

tracemalloc模块限制支持跟踪多个不同地址空间内的内存分配。

已添加新的DomainFilter过滤器类来根据地址空间(域)过滤块跟踪。

(由Victor Stinner在issue 26588中贡献。)

typing

从Python 3.6起,typing模块不再是临时的了,可以把它的API当成稳定版本使用。

由于typing模块在Python 3.5中是临时的,因此Python 3.6中引入的所有变动也已向后移植到Python 3.5.x。

typing模块很大提高了对范型别名的支持。例如,Dict[str, Tuple[S, T]]现在是一个有效的类型注释了。(由Guido van Rossum在Github #195中贡献。)

已添加typing.ContextManager类来展示contextlib.AbstractContextManager。 (由Brett Cannon在issue 25609中贡献。)

已添加typing.Collection类来展示collections.abc.Collection。 (由Ivan Levkivskyi在issue 27598中贡献。)

已添加typing.ClassVar类型构造,来标识类变量。如**PEP 526**中所述,封装在ClassVar中的一个变量注释暗示着一个给定的属性打算作为一个类变量使用,并且不应该在那个类的实例上设置它。(由Ivan Levkivskyi在Github #280中贡献。)

一个新的TYPE_CHECKING常量被静态类型检查器假设为True,但在运行时则为False。 (由Guido van Rossum在Github #230中贡献。)

已添加一个新的NewType()辅助函数来为注释创建轻量单值类型:

    from typing import NewType

    UserId = NewType('UserId', int)
    some_id = UserId(524313)

静态类型检查器将会把新的类型当成原始类型的一个子类。 (由Ivan Levkivskyi在Github #189中贡献。)

unicodedata

The unicodedata module now uses data from Unicode 9.0.0. (Contributed by Benjamin Peterson.)

unittest.mock

The Mock class has the following improvements:

urllib.request

If a HTTP request has a file or iterable body (other than a bytes object) but no Content-Length header, rather than throwing an error, AbstractHTTPHandler now falls back to use chunked transfer encoding. (Contributed by Demian Brecht and Rolf Krahl in issue 12319.)

urllib.robotparser

RobotFileParser now supports the Crawl-delay and Request-rate extensions. (Contributed by Nikolay Bogoychev in issue 16099.)

venv

venv accepts a new parameter --prompt. This parameter provides an alternative prefix for the virtual environment. (Proposed by Łukasz Balcerzak and ported to 3.6 by Stéphane Wirtel in issue22829.)

warnings

增加一个可选参数到 warnings.warn_explicit()函数中:引发 ResourceWarning 的已销毁对象。 同时,属性也添加到 warnings.WarningMessage 中。(由Victor Stinner在issue 26568issue 26567中提供)。

当引发 ResourceWarning 警告时,tracemalloc 模块就尝试检索分配了销毁对象的跟踪。

一个名为 example.py的例子

    import warnings

    def func():
        return open(__file__)

    f = func()
    f = None

输出命令 python3.6 -Wd -X tracemalloc=5 example.py :

    example.py:7: ResourceWarning: unclosed file <_io.TextIOWrapper name='example.py' mode='r' encoding='UTF-8'>
      f = None
    Object allocated at (most recent call first):
      File "example.py", lineno 4
          return open(__file__)
      File "example.py", lineno 6
          f = func()

“对象分配”跟踪是新的,并且只有当tracemalloc正在跟踪Python内存分配,并且 warnings 模块已经导入时才会显示。

winreg

新增64位整数类型 REG_QWORD. (Contributed by Clement Rouault in issue 23026.)

winsound

允许传递关键词参数到 Beep, MessageBeep, 和 PlaySound 方法。 (issue 27982).

xmlrpc.client

xmlrpc.client 模块现支持解压由apache XML-RPC实现用于数字和'None'的附加数据类型。(Contributed by Serhiy Storchaka in issue 26885.)

zipfile

一个新的类方法 ZipInfo.from_file() 允许从文件系统文件中生成一个 ZipInfo 实例。 一个新的方法 ZipInfo.is_dir() 能够用来检查ZipInfo 实例是否表示一个目录。 (Contributed by Thomas Kluyver in issue 26039.)

ZipFile.open() 方法现在能够将数据写入到一个ZIP文件,也能够从中提取数据。 (Contributed by Thomas Kluyver in issue 26039.)

zlib

compress() 以及 decompress() 函数现接受关键词参数。 (Contributed by Aviv Palivoda in issue 26243 and Xiang Zhang in issue 16764 respectively.)

优化

  • Python解释器现在使用16位编码而不是字节码,这使得你可以实现多种操作码的优化。(由Demur Rumed,Serhiy Storchaka和Victor Stinner在issue 26647 以及 issue 28050中贡献。)
  • asyncio.Future类现在有一种优化的C实现。(由Yury Selivanov和INADA Naoki在issue 26081中贡献。)
  • asyncio.Task类现在有一种优化的C实现。(由Yury Selivanov在issue 28544中贡献。)
  • typing模块中通过各种改进的实施(如泛型类型的缓存),使得其允许高达30倍的性能优化,并且减少了内存占用。
  • ASCII解码器的错误处理程序 surrogateescape, ignore 以及 replace 速度提高了60倍。(由Victor Stinner在issue 24870中贡献)。
  • ASCII和Latin1解码器的错误处理程序 surrogateescape 速度提高了3倍。(由Victor Stinner在issue 25227中贡献)。
  • UTF-8解码器的错误处理程序 ignore, replace, surrogateescape, surrogatepass速度提高了75倍。(由Victor Stinner在issue 25267中贡献)。
  • UTF-8解码器的错误处理程序ignore, replace and surrogateescape速度提高了15倍。由Victor Stinner在issue 25301中贡献)。
  • bytes % args现在速度可以提高到2倍。(由Victor Stinner在issue 25349中贡献)。
  • bytearray % args 现在速度是以前的2.5到5倍。(由Victor Stinner在issue 25399中贡献)。
  • bytes.fromhex()bytearray.fromhex()进行优化:现在比以前快2x到3.5x倍。(由Victor Stinner在issue 25401中贡献)。
  • bytes.replace(b'', b'.')bytearray.replace(b'', b'.')进行优化:速度可提高80%。 (由Josh Snider在issue 26574中贡献)。
  • 现在PyMem_Malloc()域(PYMEM_DOMAIN_MEM)的分配函数使用pymalloc memory allocator,而不是C库中的malloc()函数。 pymalloc分配器针对大小小于等于512字节、生命周期较短的对象进行了优化,而当需要占用较大内存块时则使用malloc()。 (由Victor Stinner在issue 26249中贡献)。
  • 当对大量小对象进行反序列化时,pickle.load()pickle.loads()的速度可提高10%。(由Victor Stinner在issue 27056中贡献)。
  • 与传递位置参数相比,将关键字参数传递给函数会带来额外的开销。 现在在通过使用Argument Clinic实现的扩展功能中,这种开销将会显著的降低。(由Serhiy Storchaka在issue 27574中贡献)。
  • glob模块中的glob()iglob()进行优化;使得它们现在大概快了3-6倍。(由Serhiy Storchaka在issue 25596中贡献)。
  • 使用os.scandir()pathlib中的glob进行优化;使它大概快了1.5-4倍。(由Serhiy Storchaka在issue 26032中贡献)。
  • xml.etree.ElementTree中解析、迭代和深拷贝的性能有了显著的提高。 (由Serhiy Storchaka在issue 25638issue 25873issue 25869中贡献。)
  • 由浮点数和小数创建fractions.Fraction实例的速度提高了2到3倍。(由Serhiy Storchaka在issue 25971中贡献。)

构建和C API变动

其他改进

$ ./python -VV

    Python 3.6.0b4+ (3.6:223967b49e49+, Nov 21 2016, 20:55:04)
    [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)]

弃用的模块,包以及函数

新的关键词

在后续的Python 3.7 中,asyncawait 将作为关键字使用, 因此不再建议使用它们作为变量名,类名,函数名以及模块名称。 详见Python 3.5**PEP492**. 从 Python 3.6 开始, asyncawait的使用将会引发DeprecationWarning

已弃用的 Python 行为

Python 3.7 中, 在生成器中引发StopIteration异常,现在将会导致DesprecationWarning, 并且触发`RuntimeError`. 查阅PEP 479: Change StopIteration handlinginside generators获得相关细节.

__aiter__()方法现在被期望返回异步迭代器, 而不是之前版本中的可等待迭代器,在 Python 3.6 中调用__aiter__()将会触发DeprecationWarning。 Python 3.7 将会移除其的后向兼容性。(Contributed by Yury Selivanov in issue27243.)

反斜杠对现在不能再作为有效的转义字符串使用,其会导致 DeprecationWarning. 在接下来的几个Python版本,其最终会成为一个语法错误 SyntaxError。(Contributed by Emanuel Barry in issue 27364.)

在执行相对引用, 且__spec____package__未定义时,转而调用__name____path__模块的行为 , 现在将会引发ImportWarning异常. (Contributed by Rose Ames in issue 25791.)

弃用的 Python 模块,函数和方法

asynchat

为了支持asyncioasynchat已被弃用。(Contributed by Mariatta in issue 25002.)

asyncore

为了支持asyncio模块. asyncore模块已被弃用. (Contributed by Mariatta in issue 25002.),

dbm

与其他dbm模块的的实现方式不同, dbm.dumb模块可以通过'rw'模式创建数据库 并允许通过'r'模式来修改数据库,不过这种行为现在将被弃用,在Python 3.8 将会被移除。(Contributed by Serhiy Storchaka in issue 21708.)

distutils

Distribution构造器中extra_path参数现在被认为是过时的,如果在 Python 3.6 中对其进行 设置的话将会引发一个警告。 对这个参数的支持将会在后续 Python 版本中移除。详情请参阅issue 27919

grp

getgrgid()中对非整数参数的支持,现在已被移除。(Contributed by Serhiy Storchaka in issue 26129.)

importlib

为了用来在之前的版本中支持 `importlib.abc.Loader.exec_module()`importlib.machinery.SourceFileLoader.load_module()`importlib.machin ery.SourcelessFileLoader.load_module()`,所以他们是 importlib`importlib.abc.Loader.load_module()` 仅存的未被弃用的实现方式, 不过在 Python 3.6 中,其也已经被弃用。

importlib.machinery.WindowsRegistryFinder类已被弃用。 在 Python 3.6.0 中,它被移动到 sys.meta_path中, 不过在将来这可能会发生变化。

os

os中对作为路径的通用bytes-like objectscompile()以及对类函数的非正式支持,现在已经弃用。

re

对正则式中间的内联标志 (?letters)的支持已被弃用,并将在后续 Python 版本中移除。对正则式开头的标志的支持仍然被保留。 (Contributed by Serhiy Storchaka in issue 22493.)

ssl

OpenSSL 0.9.8, 1.0.0 和 1.0.1 已被弃用,不再支持。以后ssl模块至少需要 OpenSSL 1.0.2 或者 OpenSSL 1.1.0

为了支持context, SSL的相关参数如:certfile, keyfile and check_hostnameftplib, http.client, imaplib, poplib, 和 smtplib 已被弃用。(Contributed by Christian Heimes in issue 28022.)

ssl的部分协议及函数,现已被弃用。后续的 OpenSSL 版本中,部分现有特征将不再可用。 为了引入新的API,其他的特征也已经被弃用。 (Contributed by Christian Heimes in issue 28022issue26470.)

tkinter

tkinter.tix模块已被弃用。 原tkinter的使用者,可以使用 tkinter.ttk来代替。

venv

为了引入python3 -m venv命令,pyvenv 已被弃用。 这可以防止混淆何种 Python 解释器将被pyvenv连接 以及何种 Python 解释器将被用在虚拟环境中。(Contributed by Brett Cannon in issue 25154.)

Deprecated functions and types of the C API

Undocumented functions PyUnicode_AsEncodedObject(), PyUnicode_AsDecodedObject(), PyUnicode_AsEncodedUnicode() and PyUnicode_AsDecodedUnicode() are deprecated now. Use the generic codec based API instead.

Deprecated Build Options

The --with-system-ffi configure flag is now on by default on non-macOS UNIX platforms. It may be disabled by using --without-system-ffi, but using the flag is deprecated and will not be accepted in Python 3.7. macOS is unaffected by this change. Note that many OS distributors already use the `--with-system- ffi` flag when building their system Python.

Removed

API and Feature Removals

  • Unknown escapes consisting of '\' and an ASCII letter in regular expressions will now cause an error. In replacement templates for re.sub() they are still allowed, but deprecated. The re.LOCALE flag can now only be used with binary patterns.
  • inspect.getmoduleinfo() was removed (was deprecated since CPython 3.3). inspect.getmodulename() should be used for obtaining the module name for a given path. (Contributed by Yury Selivanov in issue 13248.)
  • traceback.Ignore class and traceback.usage, traceback.modname, traceback.fullmodname, traceback.find_lines_from_code, traceback.find_lines, traceback.find_strings, traceback.find_executable_lines methods were removed from the traceback module. They were undocumented methods deprecated since Python 3.2 and equivalent functionality is available from private methods.
  • The tk_menuBar() and tk_bindForTraversal() dummy methods in tkinter widget classes were removed (corresponding Tk commands were obsolete since Tk 4.0).
  • The open() method of the zipfile.ZipFile class no longer supports the 'U' mode (was deprecated since Python 3.4). Use io.TextIOWrapper for reading compressed text files in universal newlines mode.
  • The undocumented IN, CDROM, DLFCN, TYPES, CDIO, and STROPTS modules have been removed. They had been available in the platform specific Lib/plat-*/ directories, but were chronically out of date, inconsistently available across platforms, and unmaintained. The script that created these modules is still available in the source distribution at Tools/scripts/h2py.py.
  • The deprecated asynchat.fifo class has been removed.

移植到Python 3.6

本节列出了与之前版本相比,一些特性的更改和bug的修复,这些可能会影响到你代码的编写。

'python'命令行操作变更

  • 默认情况下,用COUNT_ALLOCSSHOW_ALLOC_COUNTSHOW_TRACK_COUNT等宏定义的特殊python输出是关闭的。 它可以使用-X showalloccount选项重新启用. 它现在输出到stderr而不是stdout。 (由Serhiy Storchaka撰写在 issue 23034.)

Changes in the Python API

  • open() 'U' 模式不再允许使用'+'拼接. (由Jeff Balogh and John O'Connor撰写在 issue 2091.)

  • sqlite3 不允许在DDL语句之前隐式地提交打开的事务。

  • 在Linux系统上, os.urandom() 现在为了增强安全性,系统会一直阻塞直到系统urandom熵池被初始化。

  • importlib.abc.Loader.exec_module() 被定义时, importlib.abc.Loader.create_module() 也必须被定义.

  • PyErr_SetImportError() 现在被设置为TypeError当它的 msg 参数没有设置。 以前只返回“NULL”。

  • The format of the co_lnotab attribute of code objects changed to support a negative line number delta. By default, Python does not emit bytecode with a negative line number delta. Functions using frame.f_lineno, PyFrame_GetLineNumber() or PyCode_Addr2Line() are not affected. Functions directly decoding co_lnotab should be updated to use a signed 8-bit integer type for the line number delta, but this is only required to support applications using a negative line number delta. See Objects/lnotab_notes.txt for the co_lnotab format and how to decode it, and see the PEP 511 for the rationale.

  • compileall模块中的函数现在返回布尔类型的值,而不是用10来表示成功或失败. 由于布尔值是整数的子类,如果你对'1'或'0'进行身份检查,这只应该是一个问题。 查看issue 25768.

  • 读取urllib.parse.urlsplit()和[urlparse()]的port属性现在引发超出范围值的ValueError ,而不是返回None. 查看 issue 20059.

  • imp 模块现在代替原来的PendingDeprecationWarning抛出DeprecationWarning告警 .

  • 以下模块已将缺少的API添加到其 __all__ 属性中,匹配文档说明API: calendar, cgi, csv, ElementTree, enum, fileinput, ftplib, logging, mailbox, mimetypes, optparse, plistlib, smtpd, subprocess, tarfile, threading and wave. 这意味着在使用import *引入时,有一定的变化 . (由Joel Taddei and Jacek Kołodziej i撰写在issue 23883.)

  • 当执行相对导入时,如果__package__不等于__spec __。parent,那么 ImportWarning 警告将被抛出. (由 Brett Cannon 撰写在issue 25791.)

  • 当执行相对导入并且没有已知父包时,则将抛出ImportError异常。 以前,是抛出SystemError异常。 (由Brett Cannon 撰写在 issue 18018.)

  • 基于socketserver模块的服务器,包括http.serverxmlrpc.server和[wsgiref.simple_server] ,现在只捕获从Exception派生的异常。 因此,如果一个请求处理程序引发了[SystemExit]或[KeyboardInterrupt]] 300异常,则handle_error() 异常不再被调用,同时异常会终止单线程的服务器。 (由Martin Panter 撰写在issue 23430.)

  • 如果用户没有相关权限,spwd.getspnam()现在抛出 PermissionError 异常,代替原来的KeyError.

  • (如 EBADF) 这样的底层调用错误,socket.socket.close()方法现在会抛出异常。 (由Martin Panter撰写于issue 26685.)

  • The decode_data argument for the smtpd.SMTPChannel and smtpd.SMTPServer constructors is now False by default. This means that the argument passed to process_message() is now a bytes object by default, and process_message() will be passed keyword arguments. Code that has already been updated in accordance with the deprecation warning generated by 3.5 will not be affected.

  • All optional arguments of the dump(), dumps(), load() and loads() functions and JSONEncoder and JSONDecoder class constructors in the json module are now keyword-only. (Contributed by Serhiy Storchaka in issue 18726.)

  • Subclasses of type which don't override type.__new__ may no longer use the one-argument form to get the type of an object.

  • As part of PEP 487, the handling of keyword arguments passed to type (other than the metaclass hint, metaclass) is now consistently delegated to object.__init_subclass__(). This means that type.__new__() and type.__init__() both now accept arbitrary keyword arguments, but object.__init_subclass__() (which is called from type.__new__()) will reject them by default. Custom metaclasses accepting additional keyword arguments will need to adjust their calls to type.__new__() (whether direct or via super) accordingly.

  • In distutils.command.sdist.sdist, the default_format attribute has been removed and is no longer honored. Instead, the gzipped tarfile format is the default on all platforms and no platform-specific selection is made. In environments where distributions are built on Windows and zip distributions are required, configure the project with a setup.cfg file containing the following: ``` [sdist]

    formats=zip

```

This behavior has also been backported to earlier Python versions by Setuptools 26.0.0.

  • In the urllib.request module and the http.client.HTTPConnection.request() method, if no Content-Length header field has been specified and the request body is a file object, it is now sent with HTTP 1.1 chunked encoding. If a file object has to be sent to a HTTP 1.0 server, the Content-Length value now has to be specified by the caller. (Contributed by Demian Brecht and Rolf Krahl with tweaks from Martin Panter in issue 12319.)

  • The DictReader now returns rows of type OrderedDict. (Contributed by Steve Holden in issue 27842.)

  • The crypt.METHOD_CRYPT will no longer be added to crypt.methods if unsupported by the platform. (Contributed by Victor Stinner in issue 25287.)

  • The verbose and rename arguments for namedtuple() are now keyword-only. (Contributed by Raymond Hettinger in issue 25628.)

  • On Linux, ctypes.util.find_library() now looks in LD_LIBRARY_PATH for shared libraries. (Contributed by Vinay Sajip in issue 9998.)

  • The imaplib.IMAP4 class now handles flags containing the ']' character in messages sent from the server to improve real-world compatibility. (Contributed by Lita Cho in issue 21815.)

  • The mmap.write() function now returns the number of bytes written like other write methods. (Contributed by Jakub Stasiak in issue 26335.)

  • The pkgutil.iter_modules() and pkgutil.walk_packages() functions now return ModuleInfo named tuples. (Contributed by Ramchandra Apte in issue 17211.)

  • re.sub() now raises an error for invalid numerical group references in replacement templates even if the pattern is not found in the string. The error message for invalid group references now includes the group index and the position of the reference. (Contributed by SilentGhost, Serhiy Storchaka in issue 25953.)

  • zipfile.ZipFile will now raise NotImplementedError for unrecognized compression values. Previously a plain RuntimeError was raised. Additionally, calling ZipFile methods on a closed ZipFile or calling the write() method on a ZipFile created with mode 'r' will raise a ValueError. Previously, a RuntimeError was raised in those scenarios.

  • when custom metaclasses are combined with zero-argument super() or direct references from methods to the implicit __class__ closure variable, the implicit __classcell__ namespace entry must now be passed up to type.__new__ for initialisation. Failing to do so will result in a DeprecationWarning in 3.6 and a RuntimeWarning in the future.

在C API上的改动

CPython 字节码的更改

在Python 3.6中将会出现几个关于字节码要更新。 3.6.


(C) Copyright 2001-2016, Python 软件基金会版权所有. Python软件基金会是一个非营利性组织. 欢迎捐赠

© PyCN技术评论. Built using Pelican. Theme by Giulio Fidente on github.