Python 3.13 有什么新变化

编者:

Thomas Wouters

本文介绍了 Python 3.13 相比 3.12 增加的新特性。 Python 3.13 将于 2024 年 10 月 1 日发布。 要获取详细信息,可参阅 changelog

参见

PEP 719 -- Python 3.13 发布计划

备注

预发布版用户应当了解到此文档目前处于草稿状态。 它将随着 Python 3.13 的发步进程不断更新,因此即使已经阅读过较早的版本也仍然值得再次查看。

摘要 -- 发布重点

Python 3.13 将是 Python 编程语言的最新稳定发布版,包含多项针对语言、实现和标准库的改变。 最大的变化包括一个新的 交互式解释器,以及对于在 自由线程模式 (PEP 703) 下运行和 即时编译器 (PEP 744) 的实验性支持。

错误消息继续得到改进,回溯信息现在默认使用彩色高亮显示。 locals() 内置函数现在对于修改所返回的映射具有 更细化的语法,并且类型形参现在支持设置默认值。

针对标准库的改变包括移除已弃用的 API 和模块,以及用户友好度和正确性方面的常规提升。 一些旧式标准库模块自 Python 3.11 起被弃用 (PEP 594) 之后现在 已被移除

本文并不试图提供所有新特性的完整规范说明,而是提供一个方便的概览。 要了解完整细节请参阅相应文档,如 标准库参数语言参考。 要了解某项改变的完整实现和设计理念,请参阅相应新特性的 PEP;但请注意一旦某项特性已完全实现则相应 PEP 通常不会再继续更新。 请参阅 迁移到 Python 3.13 了解如何从较早 Python 进行升级的指导。


解释器的改进:

对 Python 数据模型的改进:

  • __static_attributes__ 存储了可在一个类体的任何函数中通过 self.X 来访问的属性名称。

  • __firstlineno__ 记录了一个类定义的首行的行号。

标准库中的重大改进:

安全改进:

C API 的改进:

  • 现在 Py_mod_gil 槽位被用来指明一个扩展模块支持在禁用 GIL 的情况下运行。

  • 增加了 PyTime C API,提供了对系统时钟的访问。

  • PyMutex 是新增的轻量级互斥锁,只占用一个字节。

新的类型标注特性:

平台支持:

重要的移除:

  • PEP 594: 剩余的 19 个“死电池”已从标准库中移除: aifc, audioop, cgi, cgitb, chunk, crypt, imghdr, mailcap, msilib, nis, nntplib, ossaudiodev, pipes, sndhdr, spwd, sunau, telnetlib, uuxdrlib

  • 移除了 2to3 工具和 lib2to3 模块(在 Python 3.11 中已被弃用)。

  • 移除了 tkinter.tix 模块(在 Python 3.6 中已被弃用)。

  • 移除了 locale.resetlocale()

  • 移除了 typing.iotyping.re

  • 移除了链式的 classmethod 描述器。

发布计划的变化:

PEP 602 ("Annual Release Cycle for Python") 已被更新为将新发布版的完整支持 ('bugfix') 期扩展至两年。 这个更新的政策意味着:

  • Python 3.9--3.12 有一年半的完整支持,另加三年半的安全修正。

  • Python 3.13 及以后的版本有两年的完整支持,另加三年的安全修正。

新的特性

更好的交互式解释器

Python 现在默认会使用新的 interactive shell,它基于来自 PyPy 项目 的代码。 当使用从交互式终端启动 REPL 时,下列新特性将受到支持:

  • 多行编辑并保留历史记录。

  • 对 REPL 专属的命令如 help, exitquit 的直接支持,无需以函数形式调用它们。

  • 提示和回溯 默认启用彩色显示

  • 使用 F1 浏览交互式帮助并带有单独的命令历史。

  • 使用 F2 浏览去除了输出以及 >>>... 提示符的历史。

  • 使用 F3 进入“粘贴模式”以更方便地粘贴大段代码(再次按 F3 返回常规提示符)。

要禁用新的交互式 shell,可设置 PYTHON_BASIC_REPL 环境变量。 有关交互模式的详情,请参见 交互模式

(由 Pablo Galindo Salgado, Łukasz Langa 和 Lysandros Nikolaou 在 gh-111201 基于来自 PyPy 项目的代码贡献。 Windows 支持由 Dino Viehland 和 Anthony Shaw 贡献。)

改进的错误消息

  • 一个常见错误是撰写的脚本和标准库中的某个模块重名。现在出现此类错误时会显示一条更有用的错误信息:

    $ python random.py
    Traceback (most recent call last):
      File "/home/me/random.py", line 1, in <module>
        import random
      File "/home/me/random.py", line 3, in <module>
        print(random.randint(5))
              ^^^^^^^^^^^^^^
    AttributeError: module 'random' has no attribute 'randint' (consider renaming '/home/me/random.py' since it has the same name as the standard library module named 'random' and the import system gives it precedence)
    

    类似地,如果一个脚本具有与它尝试导入的第三方模块相同的名称并因此导致错误,我们也会显示一条更有帮助的错误消息:

    $ python numpy.py
    Traceback (most recent call last):
      File "/home/me/numpy.py", line 1, in <module>
        import numpy as np
      File "/home/me/numpy.py", line 3, in <module>
        np.array([1, 2, 3])
        ^^^^^^^^
    AttributeError: module 'numpy' has no attribute 'array' (consider renaming '/home/me/numpy.py' if it has the same name as a third-party module you intended to import)
    

    (由 Shantanu Jain 在 gh-95754 中贡献)。

  • 现在当向一个函数传入不正确的关键字参数时错误消息会尝试提示正确的关键字参数。

    >>> "Better error messages!".split(max_split=1)
    Traceback (most recent call last):
      File "<python-input-0>", line 1, in <module>
        "Better error messages!".split(max_split=1)
        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^
    TypeError: split() got an unexpected keyword argument 'max_split'. Did you mean 'maxsplit'?
    

    (由 Pablo Galindo Salgado 和 Shantanu Jain 在 gh-107944 中贡献。)

自由线程的 CPython

现在 CPython 具有对运行于自由线程模式的实验性支持,即禁用 global interpreter lock (GIL)。 这是一个实验性的特性因而默认是不启用的。 自由线程模式需要一个不同的可执行程序,通常名为 python3.13tpython3.13t.exe。 标记为 自由线程 的预构建二进制文件可作为官方 WindowsmacOS 安装器的一部分被安装,或者可以附带 --disable-gil 选项使用源代码来构建 CPython。

自由线程式的执行允许在可用的 CPU 核心上并行地运行线程从而充分利用可用的处理能力。 虽然并非所有软件都能自动从中受益,但在设计时将线程纳入考虑的程序在多核心硬件上运行速度会更快。 自由线程模式是实验性的 并且处于不断改进的过程中:预计会出现一些程序错误并且在单线程场景下出现明显的性能损失。 可以选择使用环境变量 PYTHON_GIL 或命令行选项 -X gil 让 CPython 的自由线程构建版支持在运行时启用 GIL。

为了检查当前解释器是否支持自由线程,python -VVsys.version 将包含 "experimental free-theading build" 字样。 可以使用新增的 sys._is_gil_enabled() 函数来检查正在运行的线程是否确实禁用了 GIL。

C-API 扩展模块需要针对自由线程构建版专门进行构建。 支持在禁用 GIL 的情况下运行的扩展应当使用 Py_mod_gil 槽位。 使用单阶段初始化的扩展应当使用 PyUnstable_Module_SetGIL() 来指明它们是支支持在禁用 GIL 的情况下运行。 导入不使用这些机制的 C 扩展将导致 GIL 被启用,除非通过 PYTHON_GIL 环境变量或 -X gil=0 选项显式地禁用 GIL。 需要 pip 24.1 或更新的版本才能在自由线程构建版中安装带有 C 扩展的软件包。

参见

PEP 703 "Making the Global Interpreter Lock Optional in CPython" 中包含了有关此项工作的理念和信息。

Porting Extension Modules to Support Free-Threading: 一份由社区维护的针对扩展开发者的移植指南。

实验性的即时 (JIT) 编译器

当 CPython 使用 --enable-experimental-jit 选项进行配置和构建时,会添加一个即时(JIT)编译器以加快某些 Python 程序的运行速度。 在 Windows 上,可使用 PCbuild/build.bat --experimental-jit 启用 JIT 或使用 --experimental-jit-interpreter 启用第 2 层级解释器。 构建要求和进一步的支持信息 包含在 Tools/jit/README.md 中。

--enable-experimental-jit 选项接受这些(可选)值,如果不带可选值地预设 --enable-experimental-jit 则默认为 yes

  • no: 禁用整个第 2 层级和 JIT 管线。

  • yes: 启用 JIT。 要在运行时禁用 JIT,则传入环境变量 PYTHON_JIT=0

  • yes-off: 构建 JIT 但默认禁用它。 要在运行时启用 JIT,则传入环境变量 PYTHON_JIT=1

  • interpreter: 启用第 2 层级解释器但是禁用 JIT。 可以在运行时传入 PYTHON_JIT=0 来禁用该解释器。

其内部架构大致如下:

  • 我们将从特化的 第 1 层级字节码 开始。 请参阅 3.11 有什么新变化 了解详情。

  • 当第 1 层级字节码达到足够热度,它将被翻译为新的纯内部的中间表示形式 (IR),称为 第 2 层级 IR,有时也称为微操作码 ("uops")。

  • 第 2 层级 IR 使用与第 1 层级相同的基于栈的虚拟机,但其指令格式更适合被翻译为机器码。

  • 在第 2 层级 IR 被解释或翻译为机器码之前,我们会预先应用一些优化通路。

  • 虽然第 2 层级解释器存在,但它主要用于对优化管线的先前阶段进行调试。可通过为 Python 配置 --enable-experimental-jit=interpreter 选项启用第 2 层级解释器。

  • 启用 JIT 时,经优化的第 2 层级 IR 将被翻译为机器码后再执行。

  • 这个机器码翻译过程使用了名为 拷贝并打补丁 的技巧。 它没有运行时依赖,但增加了构建时对 LLVM 的依赖。

参见

PEP 744

(JIT 来自 Brandt Bucher 且受到 Haoran Xu 和 Fredrik Kjolstad 论文的启发。第 2 层级 IR 来自 Mark Shannon 和 Guido van Rossum。第 2 层级解释器来自 Ken Jin。)

针对 locals() 的已定义修改语义

在历史上,改变 locals() 的返回值的预期结果是留给具体的 Python 实现来定义的。 从 Python 3.13 开始,PEP 667 标准化了 CPython 对于大多数代码执行作用域的历史行为,但也将 已优化作用域 (函数、生成器、协程、推导式和生成器表达式) 修改为显式地返回当前已局部变量的独立快照,包括局部引用的在闭包中捕获的非局部变量。

在已优化的作用域中对 locals() 语义的这项修改也会影响隐式地以 locals() 为目标的代码执行函数的默认行为,如果没有提供显式命名空间的话(例如 exec()eval() 等)。 在之前的版本中,在调用代码执行函数后是否可以通过调用 locals() 访问更改情况取决于具体的实现。 具体到 CPython 而言,此类代码通常会按预期运作,但有时可能会在基于其他代码(包括调试器和代码执行跟踪工具)的已优化作用域中失败,因为代码有可能重置该作用域中的共享快照。 现在,代码在已优化作用域中将始终针对局部变量的独立快照运行,因为在后续调用 locals() 时将永远看不到更改。 要访问在这些情况下所做的更改,现在必须将一个显式命名空间引用传递给相关的函数。 或者,也可以更新受影响的代码以使用更高层级的代码执行 API 返回结果代码执行命名空间(例如,当执行磁盘上的 Python 文件时使用 runpy.run_path() 函数)。

为确保调试器和类似工具能可靠地更新受到此变化影响的作用域中的局部变量,现在 FrameType.f_locals 将返回一个针对此种作用域中的帧的局部变量和在局部引用的非局部变量的直通写入代理对象,而不是返回一个非持续更新的具有规定义的运行时语义的共享 dict 实例。

请参阅 PEP 667 了解详情,包括相关的 C API 更改和弃用。 下文还针对受影响的 Python APIC API 提供了移植说明。

(PEP 和实现由 Mark Shannon 和 Tian Gao 在 gh-74929 中贡献。 文档更新由 Guido van Rossum 和 Alyssa Coghlan 提供。)

对移动平台的支持

PEP 730: iOS 现在是 PEP 11 所支持的平台,包括第 3 层级的 arm64-apple-iosarm64-apple-ios-simulator 等目标(分别为2013 年后的 iPhone 和 iPad 设备以及运行于 Apple silicon 硬件的 Xcode iOS 模拟器)。 x86_64-apple-ios-simulator (运行于较旧的 x86_64 硬件的 Xcode iOS 模拟器)不是第 3 层级的受支持平台,但也将尽可能地支持。 (PEP 撰写及实现由 Russell Keith-Magee 在 gh-114099 中贡献。).)

PEP 738: Android 支持正在积极开发中,但该平台尚未得到官方支持。 (PEP 撰写与实现由 Malcolm Smith 在 gh-116622 中贡献。)

参见

PEP 730, PEP 738

增量式垃圾回收

循环垃圾回收器现在是增量式的。这意味着对更大的堆进行垃圾收集的最大暂停时间会减小一个数量级以上。

现在只分两代:新的和老的。 当 gc.collect() 不是被直接调用时,GC 被发起调用的频次将略微减少。 当被发起调用时,它会回收新的一代并累加老的一代,而不是回收一代或多代。

gc.collect() 的行为略有变化:

  • gc.collect(1): 执行一次 GC 累加,而不是回收第 1 代。

  • 其他对 gc.collect() 的调用没有变化。

(由 Mark Shannon 在 gh-108362 中贡献。)

其他语言特性修改

  • 编译器现在将从文档字符串的每一行去除共有的前导空格。 这会减少 字节码缓存 的大小(例如 .pyc 文件),例如在 SQLAlchemy 2.0 的 sqlalchemy.orm.session 中文件大小将减少约 5%。 这项改变将影响各种使用了文档字符串的工具,如 doctest

    >>> def spam():
    ...     """
    ...         This is a docstring with
    ...           leading whitespace.
    ...
    ...         It even has multiple paragraphs!
    ...     """
    ...
    >>> spam.__doc__
    '\nThis is a docstring with\n  leading whitespace.\n\nIt even has multiple paragraphs!\n'
    

    (由 Inada Naoki 在 gh-81283 中贡献。)

  • 类作用域内的 标注作用域 现在可以包含 lambda 和推导式。 位于类作用域内的推导式不会内联到其父作用域中。

    class C[T]:
        type Alias = lambda: T
    

    (由 Jelle Zijlstra 在 gh-109118gh-118160 中贡献。)

  • future 语句 不再会被 __future__ 模块的相对导入触发,意味着 from .__future__ import ... 形式的语句现在只是标准的相对导入,而不会激活任何特殊特性。 (由 Jeremiah Gabriel Pascual 在 gh-118216 中贡献。)

  • 现在 global 声明当其被用于 else 代码块中时也将被允许在 except 代码块中使用。 在之前版本中这会错误地引发 SyntaxError。 (由 Irit Katriel 在 gh-111123 中贡献。)

  • 增加了新的环境变量 PYTHON_FROZEN_MODULES,它确定冻结模块是否会被导入机制所忽略,等价于 -X frozen_modules 命令行选项。 (由 Yilei Yang 在 gh-111374 中贡献。)

  • 通过新的环境变量 PYTHON_PERF_JIT_SUPPORT 和命令行选项 -X perf_jit 添加无需 帧指针 即可工作的 对 perf 性能分析器的支持。 (由 Pablo Galindo 在 gh-118518 中贡献。)

  • 可通过新的 PYTHON_HISTORY 环境变量来更改 .python_history 文件的位置。 (由 Levi Sabah, Zackery Spytz 和 Hugo van Kemenade 在 gh-73965 中贡献。)

  • 类新增了一个 __static_attributes__ 属性。 这由编译器以类属性名称的元组来填充,这些名称是从类体中的任何函数通过 self.<name> 来赋值的。 (由 Irit Katriel 在 gh-115775 中贡献。)

  • 编译器现在会在类上创建一个 __firstlineno__ 属性,其值为类定义第一行的行号。 (由 Serhiy Storchaka 在 gh-118465 中贡献。)

  • 现在 exec()eval() 内置函数接受以关键字形式传入的 globalslocals 参数。 (由 Raphael Gaschignard 在 gh-105879 中贡献。)

  • 现在 compile() 内置函数接受一个新的旗标 ast.PyCF_OPTIMIZED_AST,它类似于 ast.PyCF_ONLY_AST 但区别在于返回的 AST 是根据 optimize 参数的值进行优化的。 (由 Irit Katriel 在 gh-108113 中贡献。)

  • 增加了新的异常 PythonFinalizationError,它派生自 RuntimeError,用于当操作在 最终化 期间被阻塞时发出信号。 下列可调用对象现在将引发 PythonFinalizationError,而不是 RuntimeError:

    (由 Victor Stinner 在 gh-114570 中贡献。)

  • 允许 str.replace()count 参数为关键字参数。 (由 Hugo van Kemenade 在 gh-106487 中贡献。)

  • 现在许多函数会对将布尔值作为文件描述符参数发出警告。这可以帮助尽早发现一些错误。(由 Serhiy Storchaka 在 gh-82626 中贡献。)

  • bz2, lzma, tarfilezipfile 等模块中的已压缩和已归档文件型对象添加了 namemode 属性。 (由 Serhiy Storchaka 在 gh-115961 中贡献。)

  • property 对象上增加了 __name__ 属性。 (由 Eugene Toder 在 gh-101860 中贡献。)

新增模块

  • dbm.sqlite3: 针对 dbm 的 SQLite 后端。 (由 Raymond Hettinger 和 Erlend E. Aasland 在 gh-100414 中贡献。)

改进的模块

argparse

  • add_argument()add_parser() 方法添加了 deprecated 形参,以允许弃用命令行选项、位置参数和子命令。 (由 Serhiy Storchaka 在 gh-83648 中贡献。)

array

  • 增加了 'w' 类型码 (Py_UCS4) 表示 Unicode 字符。 它应被用来代替已弃用的 'u' 类型码。 (由 Inada Naoki 在 gh-80480 中贡献。)

  • 通过实现 clear() 方法将 array.array 注册为 MutableSequence。 (由 Mike Zimin 在 gh-114894 中贡献。)

ast

  • 现在 ast 模块中节点类型的构造器对其接受的参数要求更为严格,并在参数被省略时具有更易理解的行为。

    如果在构造实例时某个 AST 节点上的可选字段没有被作为参数包括在内,则该字段现在将被设为 None。 类似地,如果某个列表字段被省略,则该字段现在将被设为空列表,而如果某个 expr_context 字段被省略,则它将默认为 Load()。 (之前,在所有情况下,新构造的 AST 节点实例上的相应属性都将缺失。)

    在所有其他情况下,当需要的参数被省略时,节点构造器将发出 DeprecationWarning。 这在 Python 3.15 中将会引发异常。 类似地,将关键字参数传入一个未映射到 AST 节点上的字段的构造器的做法现在已被弃用,并且在 Python 3.15 中将会引发异常。

    这些更改将不会应用于用户自定义的 ast.AST 子类,除非该类选择通过设置 AST._field_types 映射的方式加入新的行为。

    (由 Jelle Zijlstra 在 gh-105858, gh-117486gh-118851 中贡献。)

  • 现在 ast.parse() 接受一个可选参数 optimize,它会被传递给 compile()。 这使得获取已优化的 AST 成为可能。 (由 Irit Katriel 在 gh-108113 中贡献。)

asyncio

  • 现在 asyncio.as_completed() 将返回一个即是 asynchronous iterator 又是基本的产生 可等待对象iterator 的对象。 由异常迭代产生的可等待对象包括被传入的原始 Task 或 Future 对象,使得将结果与正在完成的任务相关联更为容易。 (由 Justin Arthur 在 gh-77714 中贡献。)

  • 现在当服务器被关闭时 asyncio.loop.create_unix_server() 会自动移除 Unix 套接字。 (由 Pierre Ossman 在 gh-111246 中贡献。)

  • 现在当附带一个空字节串对象调用时 DatagramTransport.sendto() 将发送零长度的数据报。 现在当计算缓冲区大小时传输控制流还会将数据报标头纳入考量。 (由 Jamie Phan 在 gh-115199 中贡献。)

  • 增加了 Queue.shutdownQueueShutDown 用于管理队列终结。 (由 Laurie Opperman 和 Yves Duprat 在 gh-104228 中贡献。)

  • 增加了 Server.close_clients()Server.abort_clients() 方法,它们会以更强制的方式关闭 asyncio 服务器。 (由 Pierre Ossman 在 gh-113538 中贡献。)

  • StreamReader.readuntil() 中接受一个由分隔符组成的元组,当遇到其中之一时就会停止。 (由 Bruce Merry 在 gh-81322 中贡献。)

  • 改进了 TaskGroup 在外部的取消操作与内部的取消操作发生冲突时的行为。 例如,当嵌套两个任务分组并且两者同时在某个子任务中遇到异常时,外层的任务分组有可能被挂起,因为其内部的取消操作已由内层的任务分组进行处理。

    对于任务分组在外部被取消时同时必须引发 ExceptionGroup 的情况,现在它将调用父任务的 cancel() 方法。 这样可以确保 CancelledError 会在下一次 await 时被引发,因此取消操作不会丢失。, so the cancellation is not lost.

    这些更改的一个附加好处是现在任务组会保留取消操作计数 (cancelling())。

    为了处理某些边界情况,现在 uncancel() 可以在取消操作计数达到零时重置未写入文档的 _must_cancel 旗标。

    (受到由 Arthur Tacca 在 gh-116720 中报告的问题的启发。)

  • 当在一个未激活的 TaskGroup 上调用 TaskGroup.create_task() 时,给定的协程将被关闭 (这将防止引发有关给定的协程从未被等待的 RuntimeWarning)。 (由 Arthur Tacca 和 Jason Zhang 在 gh-115957 中贡献。)

base64

compileall

configparser

concurrent.futures

configparser

  • 现在 ConfigParser 具有对未命名节的支持,这将允许使用最高层级的键值对。 此特性可通过新增的 allow_unnamed_section 形参来启用。 (由 Pedro Sousa Lacerda 在 gh-66449 中贡献。)

copy

dbm

  • 增加 dbm.sqlite3,一个实现了 SQLite 后端的新模块,并将其设为默认的 dbm 后端。 (由 Raymond Hettinger 和 Erlend E. Aasland 在 gh-100414 中贡献。)

  • 允许通过新增的 gdbm.clear()ndbm.clear() 方法移除数据库中的所有条目。 (由 Donghee Na 在 gh-107122 中贡献。)

dis

  • dis 模块的函数的输出修改为显示跳转目标和异常处理器的逻辑标签,而不是偏移量。 可以使用新的 -O 命令行选项或 show_offsets 参数来添加偏移量。 (由 Irit Katriel 在 gh-112137 中贡献。)

  • get_instructions() 不再将缓存条目表示为单独的指令。 作为替代,它会将它们作为 Instruction 的组成部分返回,放在新的 cache_info 字段中。 传给 get_instructions()show_caches 参数已被弃用并且不再有任何效果。 (由 Irit Katriel 在 gh-112962 中贡献。)

doctest

email

  • 现在带有嵌入的换行符的标头在输出时会加上引号。 现在 generator 会拒绝序列化(写入)不正确地折叠或分隔的标头,例如将被解析为多个标头或与相邻数据合并的标头等。 如果你需要禁用此安全特性,请设置 verify_generated_headers。 (由 Bas Bloemsaat 和 Petr Viktorin 在 gh-121650 中贡献。)

  • 现在 getaddresses()parseaddr() 会在更多遇到无效 email 地址的情况下返回 ('', '') 对而不是返回可能不准确的值。 这两个函数新增了可选的 strict 形参 (默认为 True)。 要获取旧版本的行为 (接受错误格式的输入),请使用 strict=False。 可以使用 getattr(email.utils, 'supports_strict_parsing', False) 来检查 strict 形参是否可用。 (由 Thomas Dwyer 和 Victor Stinner 针对 gh-102988 贡献以改进 CVE-2023-27043 修正。)

fractions

gc

循环垃圾回收器现在是递增式的,这改变了 get_threshold()set_threshold() 以及 get_count()get_stats() 的结果的具体含义。

  • 为保持向下兼容,get_threshold() 将继续返回一个由三项组成的元组。 第一项的值是新收集项的阈值,与之前一样;第二项的值决定旧收集项被扫描的频度(默认为 10,更高的值意味着旧收集项被扫描的频度更慢)。 第三项的值没有意义且始终为零。

  • set_threshold() 会忽略第二项之后的任何项。

  • get_count()get_stats() 将继续返回相同格式的结果。 唯一的区别在于结果不再是指年轻代、中年代和老年代,现在结果是指向年轻代和中年代以及老年代的回收空间。

总而言之,尝试操纵循环 GC 的行为的代码可能无法完全如预期一样有效,但也不太可能产生什么损害。 所有其他代码都会正常执行。

glob

  • 增加了 translate(),这是个用来将具有 shell 风格通配符的路径说明转换为正则表达式的函数。 (由 Barney Gale 在 gh-72904 中贡献。)

importlib

io

ipaddress

itertools

  • batched() 新增了 strict 形参,它会在最后一批次数据小于指定批准大小时引发 ValueError。 (由 Raymond Hettinger 在 gh-113202 中贡献。)

marshal

  • 在模块函数中增加了 allow_code 形参。 传入 allow_code=False 将防止在 Python 各版本间不兼容的代码对象的序列化和反序列化。 (由 Serhiy Storchaka 在 gh-113626 中贡献。)

math

  • 新增函数 fma() 可执行合并的乘法-加法运算。 此函数只需一轮操作即可计算 x * y + z,从而避免了任何中间步骤导致的精度损失。 它包装了 C99 所提供的 fma() 函数,并且遵从针对特殊情况的 IEEE 754 "fusedMultiplyAdd" 运算规范。 (由 Mark Dickinson 和 Victor Stinner 在 gh-73468 中贡献。)

mimetypes

mmap

  • 现在 mmap 在 Windows 上当被映射的内存由于文件系统错误或访问限制而不可访问时将获得保护以避免崩溃。 (由 Jannis Weigend 在 gh-118209 中贡献。)

  • mmap 具有新的 seekable() 方法将在需要可定位的文件型对象时被使用。 现在 seek() 方法将返回一个新的绝对位置。 (由 Donghee Na 和 Sylvie Liberman 在 gh-111835 中贡献。)

  • mmap 新增了 UNIX 专属的 trackfd 形参用来控制文件描述符的复制;如为假值,则由 fileno 指定的文件描述符将不会被复制。 (由 Zackery Spytz 和 Petr Viktorin 在 gh-78502 中贡献。)

multiprocessing

os

os.path

  • 增加了 isreserved() 用于检查一个路径在当前系统中是否为保留路径。 此函数仅在 Windows 上可用。 (由 Barney Gale 在 gh-88569 中贡献。)

  • On Windows, isabs() no longer considers paths starting with exactly one slash (\ or /) to be absolute. (Contributed by Barney Gale and Jon Foster in gh-44626.)

  • 现在即使文件不可访问 realpath() 也能够解析 MS-DOS 风格的文件名。 (由 Moonsik Park 在 gh-82367 中贡献。)

pathlib

pdb

  • 现在 breakpoint()set_trace() 会立即进入调试器而不是在被执行代码的下一行进入。 这一更改可防止当 breakpoint() 位于上下文末尾 时调试器在上下文以外被中断。 (由 Tian Gao 在 gh-118579 中贡献。)

  • sys.path[0] is no longer replaced by the directory of the script being debugged when sys.flags.safe_path is set. (Contributed by Tian Gao and Christian Walther in gh-111762.)

  • zipapp is now supported as a debugging target. (Contributed by Tian Gao in gh-118501.)

  • Add ability to move between chained exceptions during post-mortem debugging in pm() using the new exceptions [exc_number] command for Pdb. (Contributed by Matthias Bussonnier in gh-106676.)

  • 以一条 pdb 命令打头的表达式和语句现在会被正确地标识并执行。 (由 Tian Gao 在 gh-108464 中贡献。)

queue

random

re

  • re.error 重命名为 PatternError 以改善准确性。 re.error 仍被保留用于向下兼容。

shutil

  • chown() 中增加了对 dir_fdfollow_symlinks 关键字参数的支持。 (由 Berker Peksag 和 Tahia K 在 gh-62308 中贡献。)

site

  • 现在 .pth 文件将先使用 UTF-8 来解码,如果 UTF-8 解码失败再使用 locale encoding。 (由 Inada Naoki 在 gh-117802 中贡献。)

sqlite3

ssl

statistics

  • 增加了用于核密度估计的 kde()。 这使得根据固定数量的离散样本估计连续概率密度函数成为可能。 (由 Raymond Hettinger 在 gh-115863 中贡献。)

  • Add kde_random() for sampling from an estimated probability density function created by kde(). (Contributed by Raymond Hettinger in gh-115863.)

subprocess

  • 现在 subprocess 模块会在更多场合下使用 posix_spawn() 函数。

    Notably, when close_fds is True (the default), posix_spawn() will be used when the C library provides posix_spawn_file_actions_addclosefrom_np(), which includes recent versions of Linux, FreeBSD, and Solaris. On Linux, this should perform similarly to the existing Linux vfork() based code.

    A private control knob subprocess._USE_POSIX_SPAWN can be set to False if you need to force subprocess to never use posix_spawn(). Please report your reason and platform details in the issue tracker if you set this so that we can improve our API selection logic for everyone. (Contributed by Jakub Kulik in gh-113117.)

sys

  • Add the _is_interned() function to test if a string was interned. This function is not guaranteed to exist in all implementations of Python. (Contributed by Serhiy Storchaka in gh-78573.)

tempfile

time

  • On Windows, monotonic() now uses the QueryPerformanceCounter() clock for a resolution of 1 microsecond, instead of the GetTickCount64() clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in gh-88494.)

  • On Windows, time() now uses the GetSystemTimePreciseAsFileTime() clock for a resolution of 1 microsecond, instead of the GetSystemTimeAsFileTime() clock which has a resolution of 15.6 milliseconds. (Contributed by Victor Stinner in gh-63207.)

tkinter

  • 增加了 tkinter 控件方法: tk_busy_hold(), tk_busy_configure(), tk_busy_cget(), tk_busy_forget(), tk_busy_current()tk_busy_status()。 (由 Miguel, klappnase 和 Serhiy Storchaka 在 gh-72684 中贡献。)

  • The tkinter widget method wm_attributes() now accepts the attribute name without the minus prefix to get window attributes, for example w.wm_attributes('alpha') and allows specifying attributes and values to set as keyword arguments, for example w.wm_attributes(alpha=0.5). (Contributed by Serhiy Storchaka in gh-43457.)

  • wm_attributes() can now return attributes as a dict, by using the new optional keyword-only parameter return_python_dict. (Contributed by Serhiy Storchaka in gh-43457.)

  • Text.count() can now return a simple int when the new optional keyword-only parameter return_ints is used. Otherwise, the single count is returned as a 1-tuple or None. (Contributed by Serhiy Storchaka in gh-97928.)

  • tkinter.ttk.Styleelement_create() 方法中增加了对 "vsapi" 元素类型的支持。 (由 Serhiy Storchaka 在 gh-68166 中贡献。)

  • 为 Tkinter 的控件增加了 after_info() 方法。 (由 Cheryl Sabella 在 gh-77020 中贡献。)

  • Add a new copy_replace() method to PhotoImage to copy a region from one image to another, possibly with pixel zooming, subsampling, or both. (Contributed by Serhiy Storchaka in gh-118225.)

  • Add from_coords parameter to the PhotoImage methods copy(), zoom() and subsample(). Add zoom and subsample parameters to the PhotoImage method copy(). (Contributed by Serhiy Storchaka in gh-118225.)

  • Add the PhotoImage methods read() to read an image from a file and data() to get the image data. Add background and grayscale parameters to the write() method. (Contributed by Serhiy Storchaka in gh-118271.)

回溯

types

  • SimpleNamespace can now take a single positional argument to initialise the namespace's arguments. This argument must either be a mapping or an iterable of key-value pairs. (Contributed by Serhiy Storchaka in gh-108191.)

typing

unicodedata

venv

  • Add support for creating source control management (SCM) ignore files in a virtual environment's directory. By default, Git is supported. This is implemented as opt-in via the API, which can be extended to support other SCMs (EnvBuilder and create()), and opt-out via the CLI, using --without-scm-ignore-files. (Contributed by Brett Cannon in gh-108125.)

warnings

xml

zipimport

  • Add support for ZIP64 format files. Everybody loves huge data, right? (Contributed by Tim Hatch in gh-94146.)

性能优化

  • The new incremental garbage collector means that maximum pause times are reduced by an order of magnitude or more for larger heaps. (Contributed by Mark Shannon in gh-108362.)

  • Several standard library modules have had their import times significantly improved. For example, the import time of the typing module has been reduced by around a third by removing dependencies on re and contextlib. Other modules to enjoy import-time speedups include email.utils, enum, functools, importlib.metadata, and threading. (Contributed by Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas, and others in gh-109653.)

  • textwrap.indent() is now around 30% faster than before for large input. (Contributed by Inada Naoki in gh-107369.)

  • The subprocess module now uses the posix_spawn() function in more situations, including when close_fds is True (the default) on many modern platforms. This should provide a notable performance increase when launching processes on FreeBSD and Solaris. See the subprocess section above for details. (Contributed by Jakub Kulik in gh-113117.)

被移除的模块与 API

PEP 594: Remove "dead batteries" from the standard library

PEP 594 proposed removing 19 modules from the standard library, colloquially referred to as 'dead batteries' due to their historic, obsolete, or insecure status. All of the following modules were deprecated in Python 3.11, and are now removed:

  • aifc

  • audioop

  • chunk

  • cgicgitb

    • cgi.FieldStorage can typically be replaced with urllib.parse.parse_qsl() for GET and HEAD requests, and the email.message module or the multipart library for POST and PUT requests.

    • cgi.parse() can be replaced by calling urllib.parse.parse_qs() directly on the desired query string, unless the input is multipart/form-data, which should be replaced as described below for cgi.parse_multipart().

    • cgi.parse_header() can be replaced with the functionality in the email package, which implements the same MIME RFCs. For example, with email.message.EmailMessage:

      from email.message import EmailMessage
      
      msg = EmailMessage()
      msg['content-type'] = 'application/json; charset="utf8"'
      main, params = msg.get_content_type(), msg['content-type'].params
      
    • cgi.parse_multipart() can be replaced with the functionality in the email package, which implements the same MIME RFCs, or with the multipart library. For example, the email.message.EmailMessage and email.message.Message classes.

  • crypt and the private _crypt extension. The hashlib module may be an appropriate replacement when simply hashing a value is required. Otherwise, various third-party libraries on PyPI are available:

    • bcrypt: 用于软件和服务器的现代密码哈希算法。

    • passlib: 支持超过 over 30 种方案的综合密码哈希算法框架。

    • argon2-cffi: 安全的 Argon2 密码哈希算法。

    • legacycrypt: 针对 POSIX 加密库调用和相关功能的 ctypes 包装器。

    • crypt_r: crypt 模块的分叉,针对 crypt_r(3) 库调用和相关功能和包装器。

  • imghdr: The filetype, puremagic, or python-magic libraries should be used as replacements. For example, the puremagic.what() function can be used to replace the imghdr.what() function for all file formats that were supported by imghdr.

  • mailcap: 改用 mimetypes 模块。

  • msilib

  • nis

  • nntplib: 改用 PyPI 上的 nntplib 库。

  • ossaudiodev: 对于音频回放,改用 PyPI 上的 pygame 库。

  • pipes: 改用 subprocess 模块。

  • sndhdr: 应当使用 filetype, puremagicpython-magic 库作为替代。

  • spwd: Use the python-pam library from PyPI instead.

  • sunau

  • telnetlib,改用 PyPI 上的 telnetlib3Exscript 库。

  • uu: 改用 the base64 模块,作为一款现代化的替代。

  • xdrlib

(由 Victor Stinner 和 Zachary Ware 在 gh-104773gh-104780 中贡献。)

2to3

  • Remove the 2to3 program and the lib2to3 module, previously deprecated in Python 3.11. (Contributed by Victor Stinner in gh-104780.)

builtins

  • Remove support for chained classmethod descriptors (introduced in gh-63272). These can no longer be used to wrap other descriptors, such as property. The core design of this feature was flawed and led to several problems. To "pass-through" a classmethod, consider using the __wrapped__ attribute that was added in Python 3.10. (Contributed by Raymond Hettinger in gh-89519.)

configparser

  • Remove the undocumented LegacyInterpolation class, deprecated in the docstring since Python 3.2, and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in gh-104886.)

importlib.metadata

locale

  • Remove the locale.resetlocale() function, deprecated in Python 3.11. Use locale.setlocale(locale.LC_ALL, "") instead. (Contributed by Victor Stinner in gh-104783.)

opcode

  • Move opcode.ENABLE_SPECIALIZATION to _opcode.ENABLE_SPECIALIZATION. This field was added in 3.12, it was never documented, and is not intended for external use. (Contributed by Irit Katriel in gh-105481.)

  • Remove opcode.is_pseudo(), opcode.MIN_PSEUDO_OPCODE, and opcode.MAX_PSEUDO_OPCODE, which were added in Python 3.12, but were neither documented nor exposed through dis, and were not intended to be used externally. (Contributed by Irit Katriel in gh-105481.)

pathlib

  • Remove the ability to use Path objects as context managers. This functionality was deprecated and has had no effect since Python 3.9. (Contributed by Barney Gale in gh-83863.)

re

  • Remove the undocumented, deprecated, and broken re.template() function and re.TEMPLATE / re.T flag. (Contributed by Serhiy Storchaka and Nikita Sobolev in gh-105687.)

tkinter.tix

  • Remove the tkinter.tix module, deprecated in Python 3.6. The third-party Tix library which the module wrapped is unmaintained. (Contributed by Zachary Ware in gh-75552.)

turtle

  • Remove the RawTurtle.settiltangle() method, deprecated in the documentation since Python 3.1 and at runtime since Python 3.11. (Contributed by Hugo van Kemenade in gh-104876.)

typing

  • Remove the typing.io and typing.re namespaces, deprecated since Python 3.8. The items in those namespaces can be imported directly from the typing module. (Contributed by Sebastian Rittau in gh-92871.)

  • Remove the keyword-argument method of creating TypedDict types, deprecated in Python 3.11. (Contributed by Tomas Roun in gh-104786.)

unittest

urllib

webbrowser

  • Remove the untested and undocumented MacOSX class, deprecated in Python 3.11. Use the MacOSXOSAScript class (introduced in Python 3.2) instead. (Contributed by Hugo van Kemenade in gh-104804.)

  • Remove the deprecated MacOSXOSAScript._name attribute. Use the MacOSXOSAScript.name attribute instead. (Contributed by Nikita Sobolev in gh-105546.)

新的弃用

  • array: array'u' 格式码,自 Python 3.3 起在文档中声明弃用,自 3.13 开始发出 DeprecationWarning 并将在 Python 3.16 中移除。 请改用 'w' 格式码。 (由 Hugo van Kemenade 在 gh-80480 中贡献。)

  • ctypes: 弃用未写入文档的 ctypes.SetPointerType() 函数。 软弃用 ctypes.ARRAY() 函数并改用乘法。 (由 Victor Stinner 在 gh-105733 中贡献。)

  • decimal: 弃用 decimal.Decimal 的非标准格式说明符 "N"。 它未被写入文档并且仅在 C 实现中受支持。 (由 Serhiy Storchaka 在 gh-89902 中贡献。)

  • dis: dis.HAVE_ARGUMENT 分隔符已被弃用。 改为在 hasarg 中检查成员。 (由 Irit Katriel 在 gh-109319 中贡献。)

  • 帧对象: Calling frame.clear() on a suspended frame raises RuntimeError (as has always been the case for an executing frame). (Contributed by Irit Katriel in gh-79932.)

  • getopt and optparse modules: They are now soft deprecated: the argparse module should be used for new projects. Previously, the optparse module was already deprecated, its removal was not scheduled, and no warnings was emitted: so there is no change in practice. (Contributed by Victor Stinner in gh-106535.)

  • gettext: Emit deprecation warning for non-integer numbers in gettext functions and methods that consider plural forms even if the translation was not found. (Contributed by Serhiy Storchaka in gh-88434.)

  • glob: The undocumented glob.glob0() and glob.glob1() functions are deprecated. Use glob.glob() and pass a directory to its root_dir argument instead. (Contributed by Barney Gale in gh-117337.)

  • http.server: http.server.CGIHTTPRequestHandler now emits a DeprecationWarning as it will be removed in 3.15. Process-based CGI HTTP servers have been out of favor for a very long time. This code was outdated, unmaintained, and rarely used. It has a high potential for both security and functionality bugs. This includes removal of the --cgi flag to the python -m http.server command line in 3.15.

  • mimetypes: Passing file path instead of URL in guess_type() is soft deprecated. Use guess_file_type() instead. (Contributed by Serhiy Storchaka in gh-66543.)

  • re: Passing optional arguments maxsplit, count and flags in module-level functions re.split(), re.sub() and re.subn() as positional arguments is now deprecated. In future Python versions these parameters will be keyword-only. (Contributed by Serhiy Storchaka in gh-56166.)

  • pathlib: pathlib.PurePath.is_reserved() 已被弃用并计划在 Python 3.15 中移除。 请使用 os.path.isreserved() 来检测 Windows 上的保留路径。

  • platform: java_ver() 已被弃用并将在 3.15 中移除。 它几乎未经测试,具有令人困惑的 API,并且仅适用于 Jython 支持。 (由 Nikita Sobolev 在 gh-116349 中贡献。)

  • pydoc :弃用未记载的 pydoc.ispackage() 方法。(由Zackery Spytz在 gh-64020 中贡献。)

  • sqlite3: 向 sqlite3.connect()sqlite3.Connection 构造器传入多个位置参数的做法已被弃用。 其他的形参在 Python 3.15 中将成为仅限关键字形参。

    Deprecate passing name, number of arguments, and the callable as keyword arguments for the following sqlite3.Connection APIs:

    已弃用通过关键字参数形式为下列 sqlite3.Connection API 传入可调用对象:

    受影响的形参将在 Python 3.15 中成为仅限位置形参。

    (由 Erlend E. Aasland 在 gh-107948gh-108278 中贡献。)

  • sys: The sys._enablelegacywindowsfsencoding() function is deprecated. Replace it with the PYTHONLEGACYWINDOWSFSENCODING environment variable. (Contributed by Inada Naoki in gh-73427.)

  • tarfile :在 tarfile.TarFile 类中未记载亦未使用的 tarfile 属性现已弃用,并计划于Python 3.16版本中移除。

  • traceback: The field exc_type of traceback.TracebackException is deprecated. Use exc_type_str instead.

  • typing:

    • Creating a typing.NamedTuple class using keyword arguments to denote the fields (NT = NamedTuple("NT", x=int, y=int)) is deprecated, and will be disallowed in Python 3.15. Use the class-based syntax or the functional syntax instead. (Contributed by Alex Waygood in gh-105566.)

    • When using the functional syntax to create a typing.NamedTuple class or a typing.TypedDict class, failing to pass a value to the 'fields' parameter (NT = NamedTuple("NT") or TD = TypedDict("TD")) is deprecated. Passing None to the 'fields' parameter (NT = NamedTuple("NT", None) or TD = TypedDict("TD", None)) is also deprecated. Both will be disallowed in Python 3.15. To create a NamedTuple class with zero fields, use class NT(NamedTuple): pass or NT = NamedTuple("NT", []). To create a TypedDict class with zero fields, use class TD(TypedDict): pass or TD = TypedDict("TD", {}). (Contributed by Alex Waygood in gh-105566 and gh-105570.)

    • typing.no_type_check_decorator() is deprecated, and scheduled for removal in Python 3.15. After eight years in the typing module, it has yet to be supported by any major type checkers. (Contributed by Alex Waygood in gh-106309.)

    • typing.AnyStr is deprecated. In Python 3.16, it will be removed from typing.__all__, and a DeprecationWarning will be emitted when it is imported or accessed. It will be removed entirely in Python 3.18. Use the new type parameter syntax instead. (Contributed by Michael The in gh-107116.)

  • 用户定义函数: Assignment to a function's __code__ attribute where the new code object's type does not match the function's type is deprecated. The different types are: plain function, generator, async generator and coroutine. (Contributed by Irit Katriel in gh-81137.)

  • wave: 已弃用 wave.Wave_readwave.Wave_write 类的 getmark(), setmark()getmarkers() 方法。 它们将在 Python 3.15 中被移除。 (由 Victor Stinner 在 gh-105096 中贡献。)

计划在 Python 3.14 中移除

Python 3.15 中的待移除功能

  • http.server.CGIHTTPRequestHandler 将同 python -m http.server 中与其相关的 --cgi 旗标一起被移除。 它已经过时并且很少被使用。 不存在直接的替代品。 对于建立 Web 服务器与请求处理器的接口的任务来说 任何东西 都比 CGI 要好。

  • locale: locale.getdefaultlocale() 在 Python 3.11 中已被弃用并且原计划在 Python 3.13 中移除 (gh-90817),但移除时间已被推迟至 Python 3.15。 请改用 locale.setlocale(), locale.getencoding()locale.getlocale()。 (由 Hugo van Kemenade 在 gh-111187 中贡献。)

  • pathlib: pathlib.PurePath.is_reserved() 已被弃用并计划在 Python 3.15 中移除。 请使用 os.path.isreserved() 来检测 Windows 上的保留路径。

  • platform: java_ver() 已被弃用并将在 3.15 中移除。 它几乎未经测试,具有令人困惑的 API,并且仅适用于 Jython 支持。 (由 Nikita Sobolev 在 gh-116349 中贡献。)

  • threading: 向 threading.RLock() 传入任意参数的做法现已被弃用。 C 版本允许任意数量的 args 和 kwargs,但它们都会被忽略。 Python 版本不允许任何参数。 在 Python 3.15 中将从 threading.RLock() 移除所有参数。 (由 Nikita Sobolev 在 gh-102029 中贡献。)

  • typing.NamedTuple:

    • 创建 NamedTuple 类 (NT = NamedTuple("NT", x=int)) 的关键字参数语法从未写入文档且已被弃用,并将在 3.15 中被禁止。 请改用基于类的语法或函数语法。

    • 当使用函数式语法创建 NamedTuple 类时,不向 fields 形参传值的做法 (NT = NamedTuple("NT")) 已被弃用。 将 None 传给 fields 形参的做法 (NT = NamedTuple("NT", None)) 也已被弃用。 两者都将在 Python 3.15 中被禁止。 要创建拥有 0 个字段的 NamedTuple 类,请使用 class NT(NamedTuple): passNT = NamedTuple("NT", [])

  • typing.TypedDict: 当使用函数语法创建 TypedDict 类时,不向 fields 形参传值 (TD = TypedDict("TD")) 的行为已被弃用。 将 None 传给 fields 形参 (TD = TypedDict("TD", None)) 的行为也已被弃用。 两者都将在 Python 3.15 中被禁止。 要创建拥有 0 个字段的 TypedDict 类,请使用 class TD(TypedDict): passTD = TypedDict("TD", {})

  • wave: 已弃用 wave.Wave_readwave.Wave_write 类的 getmark(), setmark()getmarkers() 方法。 它们将在 Python 3.15 中被移除。 (由 Victor Stinner 在 gh-105096 中贡献。)

计划在 Python 3.16 中移除

计划在未来版本中移除

以下API将会被移除,尽管具体时间还未确定。

  • argparse: 嵌套参数分组和嵌套互斥分组的做法已被弃用。

  • array'u' 格式代码 (gh-57281)

  • builtins:

    • bool(NotImplemented)

    • 生成器: throw(type, exc, tb)athrow(type, exc, tb) 签名已被弃用:请改用 throw(exc)athrow(exc),即单参数签名。

    • 目前 Python 接受数字类字面值后面紧跟关键字的写法,例如 0in x, 1or x, 0if 1else 2。 它允许像 [0x1for x in y] 这样令人困惑且有歧义的表达式 (它可以被解读为 [0x1 for x in y] 或者 [0x1f or x in y])。 如果数字类字面值后面紧跟关键字 and, else, for, if, in, isor 中的一个将会引发语法警告。 在未来的版本中它将改为语法错误。 (gh-87999)

    • __index__()__int__() 方法返回非 int 类型的支持:将要求这些方法必须返回 int 的子类的实例。

    • __float__() 方法返回 float 的子类的支持:将要求这些方法必须返回 float 的实例。

    • __complex__() 方法返回 complex 的子类的支持:将要求这些方法必须返回 complex 的实例。

    • int() 委托给 __trunc__() 方法。

    • 传入一个复数作为 complex() 构造器中的 realimag 参数的做法现在已被弃用;它应当仅作为单个位置参数被传入。 (由 Serhiy Storchaka 在 gh-109218 中贡献。).)

  • calendar: calendar.Januarycalendar.February 常量已被弃用并由 calendar.JANUARYcalendar.FEBRUARY 替代。 (由 Prince Roshan 在 gh-103636 中贡献。)

  • codeobject.co_lnotab: 改用 codeobject.co_lines() 方法。

  • datetime:

    • utcnow(): 使用 datetime.datetime.now(tz=datetime.UTC)

    • utcfromtimestamp(): 使用 datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)

  • gettext: 复数值必须是一个整数。

  • importlib:

    • load_module() 方法:改用 exec_module()

    • cache_from_source() debug_override 形参已被弃用:改用 optimization 形能耐。

  • importlib.metadata:

    • EntryPoints 元组接口。

    • 返回值中隐式的 None

  • logging: the warn() method has been deprecated since Python 3.3, use warning() instead.

  • mailbox: 对 StringIO 输入和文本模式的使用已被弃用,改用 BytesIO 和二进制模式。

  • os: 在多线程的进程中调用 os.register_at_fork()

  • pydoc.ErrorDuringImport: 使用元组值作为 exc_info 形参的做法已被弃用,应使用异常实例。

  • re: 现在对于正则表达式中的数字分组引用和分组名称将应用更严格的规则。 现在只接受 ASCII 数字序列作为数字引用。 字节串模式和替换字符串中的分组名称现在只能包含 ASCII 字母和数字以及下划线。 (由 Serhiy Storchaka 在 gh-91760 中贡献。)

  • sre_compile, sre_constantssre_parse 模块。

  • shutil: rmtree()onerror 形参在 Python 3.12 中已被弃用;请改用 onexc 形参。

  • ssl 选项和协议:

    • ssl.SSLContext 不带 protocol 参数的做法已被弃用。

    • ssl.SSLContext: set_npn_protocols()selected_npn_protocol() 已被弃用:请改用 ALPN.

    • ssl.OP_NO_SSL* 选项

    • ssl.OP_NO_TLS* 选项

    • ssl.PROTOCOL_SSLv3

    • ssl.PROTOCOL_TLS

    • ssl.PROTOCOL_TLSv1

    • ssl.PROTOCOL_TLSv1_1

    • ssl.PROTOCOL_TLSv1_2

    • ssl.TLSVersion.SSLv3

    • ssl.TLSVersion.TLSv1

    • ssl.TLSVersion.TLSv1_1

  • sysconfig.is_python_build() check_home 形参已被弃用并会被忽略。

  • threading 的方法:

  • typing.Text (gh-92332)。

  • unittest.IsolatedAsyncioTestCase: 从测试用例返回不为 None 的值的做法已被弃用。

  • urllib.parse 函数已被弃用:改用 urlparse()

    • splitattr()

    • splithost()

    • splitnport()

    • splitpasswd()

    • splitport()

    • splitquery()

    • splittag()

    • splittype()

    • splituser()

    • splitvalue()

    • to_bytes()

  • urllib.request: 发起请求的 URLopenerFancyURLopener 方式已被弃用。 改用更新 urlopen() 函数和方法。

  • wsgiref: SimpleHandler.stdout.write() 不应执行部分写入。

  • xml.etree.ElementTree: 对 Element 的真值测试已被弃用。 在未来的发布版中它将始终返回 True。 建议改用显式的 len(elem)elem is not None 测试。

  • zipimport.zipimporter.load_module() 已被弃用:请改用 exec_module()

CPython 字节码的变化

  • The oparg of YIELD_VALUE is now 1 if the yield is part of a yield-from or await, and 0 otherwise. The oparg of RESUME was changed to add a bit indicating whether the except-depth is 1, which is needed to optimize closing of generators. (Contributed by Irit Katriel in gh-111354.)

C API 的变化

新的特性

构建变化

  • 现在 configure 选项 --with-system-libmpdec 默认为 yes。 捆绑的 libmpdecimal 副本将在 Python 3.15 中被移除。

  • 现在需要有 autoconf 2.71 和 aclocal 1.16.4 才能重新生成 configure 脚本。 (由 Christian Heimes 在 gh-89886 中贡献。)

  • 需要 SQLite 3.15.2 或更新的版本才能构建 sqlite3 扩展模块。 (由 Erlend Aasland 在 gh-105875 中贡献。)

  • 使用 configure --with-trace-refs (跟踪引用) 构建的 Python 现在与 Python 发布构建版和 调试构建版 是 ABI 兼容的。 (由 Victor Stinner 在 gh-108634 中贡献。)

  • 现在构建 CPython 需要带有 C11 atomic 库支持的编译器、GCC 内置 atomic 函数或 MSVC 互锁内生函数。

  • 现在 errno, fcntl, grp, md5, pwd, resource, termios, winsound, _ctypes_test, _multiprocessing.posixshmem, _scproxy, _stat, _statistics, _testconsole, _testimportmultiple_uuid C 扩展是使用 受限 C API 构建的。 (由 Victor Stinner 在 gh-85283 中贡献。)

  • 现在 wasm32-wasiPEP 11 第 2 层级的平台。 (由 Brett Cannon 在 gh-115192 中贡献。)

  • wasm32-emscripten 不再是 PEP 11 的受支持平台。 (由 Brett Cannon 在 gh-115192 中贡献。)

  • Python now bundles the mimalloc library. It is licensed under the MIT license; see mimalloc license. The bundled mimalloc has custom changes, see gh-113141 for details. (Contributed by Dino Viehland in gh-109914.)

  • On POSIX systems, the pkg-config (.pc) filenames now include the ABI flags. For example, the free-threaded build generates python-3.13t.pc and the debug build generates python-3.13d.pc.

Porting to Python 3.13

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

Python API 的变化

  • An OSError is now raised by getpass.getuser() for any failure to retrieve a username, instead of ImportError on non-Unix platforms or KeyError on Unix platforms where the password database is empty.

  • 现在 threading 模块会预期 _thread 模块具有 _is_main_interpreter 属性。 它是一个不带参数的函数并会在当前解释器为主解释器时返回 True

    Any library or application that provides a custom _thread module must provide _is_main_interpreter(), just like the module's other "private" attributes. (See gh-112826.)

  • mailbox.Maildir now ignores files with a leading dot. (Contributed by Zackery Spytz in gh-65559.)

  • pathlib.Path.glob() and rglob() now return both files and directories if a pattern that ends with "**" is given, rather than directories only. Users may add a trailing slash to match only directories.

  • The value of the mode attribute of gzip.GzipFile was changed from integer (1 or 2) to string ('rb' or 'wb'). The value of the mode attribute of the readable file-like object returned by zipfile.ZipFile.open() was changed from 'r' to 'rb'. (Contributed by Serhiy Storchaka in gh-115961.)

  • functools.partial now emits a FutureWarning when it is used as a method. Its behavior will be changed in future Python versions. Wrap it in staticmethod() if you want to preserve the old behavior. (Contributed by Serhiy Storchaka in gh-121027.)

  • Calling locals() in an optimized scope now produces an independent snapshot on each call, and hence no longer implicitly updates previously returned references. Obtaining the legacy CPython behaviour now requires explicit calls to update the initially returned dictionary with the results of subsequent calls to locals(). Code execution functions that implicitly target locals() (such as exec and eval) must be passed an explicit namespace to access their results in an optimized scope. (Changed as part of PEP 667.)

  • Calling locals() from a comprehension at module or class scope (including via exec or eval) once more behaves as if the comprehension were running as an independent nested function (i.e. the local variables from the containing scope are not included). In Python 3.12, this had changed to include the local variables from the containing scope when implementing PEP 709. (Changed as part of PEP 667.)

  • Accessing FrameType.f_locals in an optimized scope now returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly with dict or the proxy's .copy() method. (Changed as part of PEP 667.)

C API 的变化

  • Python.h no longer includes the <ieeefp.h> standard header. It was included for the finite() function which is now provided by the <math.h> header. It should now be included explicitly if needed. Remove also the HAVE_IEEEFP_H macro. (Contributed by Victor Stinner in gh-108765.)

  • Python.h no longer includes these standard header files: <time.h>, <sys/select.h> and <sys/time.h>. If needed, they should now be included explicitly. For example, <time.h> provides the clock() and gmtime() functions, <sys/select.h> provides the select() function, and <sys/time.h> provides the futimes(), gettimeofday() and setitimer() functions. (Contributed by Victor Stinner in gh-108765.)

  • On Windows, Python.h no longer includes the <stddef.h> standard header file. If needed, it should now be included explicitly. For example, it provides offsetof() function, and size_t and ptrdiff_t types. Including <stddef.h> explicitly was already needed by all other platforms, the HAVE_STDDEF_H macro is only defined on Windows. (Contributed by Victor Stinner in gh-108765.)

  • If the Py_LIMITED_API macro is defined, Py_BUILD_CORE, Py_BUILD_CORE_BUILTIN and Py_BUILD_CORE_MODULE macros are now undefined by <Python.h>. (Contributed by Victor Stinner in gh-85283.)

  • The old trashcan macros Py_TRASHCAN_SAFE_BEGIN and Py_TRASHCAN_SAFE_END were removed. They should be replaced by the new macros Py_TRASHCAN_BEGIN and Py_TRASHCAN_END.

    A tp_dealloc function that has the old macros, such as:

    static void
    mytype_dealloc(mytype *p)
    {
        PyObject_GC_UnTrack(p);
        Py_TRASHCAN_SAFE_BEGIN(p);
        ...
        Py_TRASHCAN_SAFE_END
    }
    

    应当按照以下方式迁移到新版宏:

    static void
    mytype_dealloc(mytype *p)
    {
        PyObject_GC_UnTrack(p);
        Py_TRASHCAN_BEGIN(p, mytype_dealloc)
        ...
        Py_TRASHCAN_END
    }
    

    Note that Py_TRASHCAN_BEGIN has a second argument which should be the deallocation function it is in. The new macros were added in Python 3.8 and the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel in gh-105111.)

  • Functions PyDict_GetItem(), PyDict_GetItemString(), PyMapping_HasKey(), PyMapping_HasKeyString(), PyObject_HasAttr(), PyObject_HasAttrString(), and PySys_GetObject(), which clear all errors which occurred when calling them, now report them using sys.unraisablehook(). You may replace them with other functions as recommended in the documentation. (Contributed by Serhiy Storchaka in gh-106672.)

  • PyCode_GetFirstFree() is an unstable API now and has been renamed to PyUnstable_Code_GetFirstFree(). (Contributed by Bogdan Romanyuk in gh-115781.)

  • The effects of mutating the dictionary returned from PyEval_GetLocals() in an optimized scope have changed. New dict entries added this way will now only be visible to subsequent PyEval_GetLocals() calls in that frame, as PyFrame_GetLocals(), locals(), and FrameType.f_locals no longer access the same underlying cached dictionary. Changes made to entries for actual variable names and names added via the write-through proxy interfaces will be overwritten on subsequent calls to PyEval_GetLocals() in that frame. The recommended code update depends on how the function was being used, so refer to the deprecation notice on the function for details. (Changed as part of PEP 667.)

  • Calling PyFrame_GetLocals() in an optimized scope now returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly (e.g. with PyDict_Copy()) or by calling the new PyEval_GetFrameLocals() API. (Changed as part of PEP 667.)

  • PyFrame_FastToLocals() and PyFrame_FastToLocalsWithError() no longer have any effect. Calling these functions has been redundant since Python 3.11, when PyFrame_GetLocals() was first introduced. (Changed as part of PEP 667.)

  • PyFrame_LocalsToFast() no longer has any effect. Calling this function is redundant now that PyFrame_GetLocals() returns a write-through proxy for optimized scopes. (Changed as part of PEP 667.)

Removed C APIs

已弃用的 C API

计划在 Python 3.14 中移除

Python 3.15 中的待移除功能

计划在未来版本中移除

以下 API 已被弃用,将被移除,但目前尚未确定移除日期。

回归测试的变化

  • 现在使用 configure --with-pydebug 编译的 Python 将支持 -X presite=package.module 命令行选项。 如果被使用,它指明一个模块应当在解释器生命周期开始时,即 site.py 被执行之前被导入。 (由 Łukasz Langa 在 gh-110769 中贡献。)