Python 3.13 有什么新变化

编者:

Adam Turner 和 Thomas Wouters

本文介绍了 Python 3.13 相比 3.12 增加的新我。 Python 3.13 已于 2024 年 10 月 7 日发布。 要获取详细信息,可参阅 更新日志

参见

PEP 719 -- 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 数据模型的改进:

标准库中的重大改进:

安全改进:

C API 的改进:

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

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

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

  • 新增了 一套函数 用于在 C API 中生成 PEP 669 监控事件。

新的类型标注特性:

平台支持:

重要的移除:

  • PEP 594: 剩余的 19 个“死电池”(老旧 stdlib 模块)已从标准库中移除: 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。 标记为 free-threaded 的预构建二进制文件可作为官方 WindowsmacOS 安装器的一部分被安装,或者可以附带 --disable-gil 选项使用源代码来构建 CPython。

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

这项工作成为可能要感谢许多个人和组织,包括针对 Python 和第三方项目测试并启用自由线程支持的庞大的贡献者社区。 重要的贡献者包括:Sam Gross, Ken Jin, Donghee Na, Itamar Oren, Matt Page, Brett Simmers, Dino Viehland, Carl Meyer, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou 及其他许多人。 有许多贡献者受雇于 Meta,该公司提供了大量的工程资源来支持此项目。

参见

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 11 所支持的平台,包括位于第 3 层级的 aarch64-linux-androidx86_64-linux-android 等目标。 32 位的目标 arm-linux-androideabii686-linux-android 不是第 3 层级的受支持平台,但也将尽可能地支持。 (PEP 撰写及实现由 Malcolm Smith 在 gh-116622 中贡献。)

参见

PEP 730, PEP 738

其他语言特性修改

  • 编译器现在将从文档字符串的每一行去除共有的前导空格。 这会减少 字节码缓存 的大小(例如 .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 中贡献。)

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

  • 增加了新的异常 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 中贡献。)

新增模块

  • 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

concurrent.futures

configparser

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

copy

ctypes

  • 作为必要的内部重构的一个后果,内部元类的初始化现在将发生于 __init__ 中而不是 __new__ 中。 这会影响子类化这些内部元类以提供自定义初始化的项目。 一般而言:

    • 调用 super().__new__ 之后在 __new__ 中完成的自定义逻辑应当移至 __init__

    • 要创建一个类,需调用相应的元类,而不仅是该元类的 __new__ 方法。

    请参阅 gh-124520 了解相关讨论和对某些受影响项目的修改的链接。

  • ctypes.Structure objects have a new _align_ attribute which allows the alignment of the structure being packed to/from memory to be specified explicitly. (Contributed by Matt Sanderson in gh-112433)

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=Falsegetattr(email.utils, 'supports_strict_parsing', False) 可被用于检查 strict 形参是否可用。 (由 Thomas Dwyer 和 Victor Stinner 针对 gh-102988 贡献以改进 CVE 2023-27043 修正。)

fractions

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 中贡献。)

  • 在 Windows 上,isabs() 将不再把以恰好一个斜杠 (\/) 开头的路径视为绝对路径。 (由 Barney Gale 和 Jon Foster 在 gh-44626 中贡献。)

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

pathlib

pdb

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

  • 当设置了 sys.flags.safe_pathsys.path[0] 将不会再被替换为被调试脚本的目录。 (由 Tian Gao 和 Christian Walther 在 gh-111762 中贡献。)

  • 现在支持将 zipapp 作为调试目标。 (由 Tian Gao 在 gh-118501 中贡献。)

  • 添加了在 pm() 中进行事后调试期间使用 Pdb 新增的 exceptions [exc_number] 命令在串连的异常之间移动的能力。 (由 Matthias Bussonnier 在 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 中贡献。)

  • 增加了 kde_random() 用来从 kde() 创建的估计概率密度函数进行取样。 (由 Hettinger 在 gh-115863 中贡献。)

subprocess

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

    需要注意的是,当 close_fdsTrue 时(默认值),则将在 C 库提供了 posix_spawn_file_actions_addclosefrom_np() 时使用 posix_spawn(),这包括近期的 Linux, FreeBSD 和 Solaris 版本。 在 Linux,其性能应当与现有的 Linux vfork() 基础代码类似。

    如果你需要强制 subprocess 绝不使用 posix_spawn() 可以将私有的控制节点 subprocess._USE_POSIX_SPAWN 设为 False。 如果你这样设置的话请在 issue tracker 中报告你的理由和平台相关的细节以便我们能够为大家改进 API 的选择逻辑。 (由 Jakub Kulik 在 gh-113117 中贡献。)

sys

  • 增加了 _is_interned() 函数用于检测字符串是否被内部化。 此函数不保证在所有的 Python 实现中均存在。 (由 Serhiy Storchaka 在 gh-78573 中贡献。)

tempfile

time

  • 在 Windows 上,monotonic() 现在将使用精度为 1 微秒的 QueryPerformanceCounter() 时钟,而不是精度只有 15.6 毫秒的 GetTickCount64() 时钟。 (由 Victor Stinner 在 gh-88494 中贡献。)

  • 在 Windows 上,time() 现在将使用精度为 1 微秒的 GetSystemTimePreciseAsFileTime() 时钟,代替精度为 15.6 毫秒的 GetSystemTimeAsFileTime() 时钟。 (由 Victor Stinner 在 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 中贡献。)

  • 现在 tkinter 控件 wm_attributes() 接受不带负号前缀的属性名称来获取窗口属性,例如 w.wm_attributes('alpha') 并允许指定属性和值以关键字参数形式来设置,例如 w.wm_attributes(alpha=0.5)。 (由 Serhiy Storchaka 在 gh-43457 中贡献。)

  • 通过使用新的可选关键字形参 return_python_dict,现在 wm_attributes() 可将属性作为 dict 返回。 (由 Serhiy Storchaka 在 gh-43457 中贡献。)

  • 现在当使用新的可选仅限关键字形参 return_intsText.count() 可以返回一个简单的 int。 在其他情况下,将以 1 个元素的元组形式返回单个计数值或者 None。 (由 Serhiy Storchaka 在 gh-97928 中贡献。)

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

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

  • PhotoImage 新增 copy_replace() 方法用于将一个图像的某个区域拷贝到另一个图像,可能带有像素缩放、子采样,或两者皆有。 (由 Serhiy Storchaka 在 gh-118225 中贡献。)

  • PhotoImage 的方法 copy(), zoom()subsample() 增加了 from_coords 形参。 为 PhotoImage 的方法 copy() 增加了 zoomsubsample 形参。 (由 Serhiy Storchaka 在 gh-118225 中贡献。)

  • 增加了 PhotoImage 方法 read() 用于从文件读取图像以及 data() 用于获取图像数据。 为 write() 方法增加了 backgroundgrayscale 形参。 (由 Serhiy Storchaka 在 gh-118271 中贡献。).)

回溯

types

  • 现在 SimpleNamespace 可以接受单个位置参数来初始化命名空间的各个参数值。 该参数必须为映射或键值对的可迭代对象。 (由 Serhiy Storchaka 在 gh-108191 中贡献。)

typing

unicodedata

  • 将 Unicode 数据库更新到 15.1.0 版。 (由 James Gerity 在 gh-109559 中贡献。)

venv

  • 增加了对在虚拟环境目录中添加源码控制管理 (SCM) 忽略文件的支持。 在默认情况下,Git 已受到支持。 此特性是以可被扩展为支持其他 SCM 的通过 API 选择启用 (EnvBuildercreate()),并通过 CLI 使用 --without-scm-ignore-files 选择禁用的方式实现的。 (由 Brett Cannon 在 gh-108125 中贡献。)

warnings

xml

zipimport

  • 增加了对 ZIP64 格式的文件的支持。 大家都喜欢更庞大的数据,对吧? (由 Tim Hatch 在 gh-94146 中贡献。).)

性能优化

  • 一些标准库模块的导入时间得到了显著改善。 例如,typing 模块的导入时间通过移除对 recontextlib 的依赖而减少了大约三分之一。 其他获得导入时间加速的模块包括 email.utils, enum, functools, importlib.metadatathreading。 (由 Alex Waygood, Shantanu Jain, Adam Turner, Daniel Hollas 等人在 gh-109653 中贡献。)

  • 现在对于大量输入 textwrap.indent() 相比之前可提速大约 30%。 (由 Inada Naoki 在 gh-107369 中贡献。)

  • 现在 subprocess 模块会在更多场合下使用 posix_spawn() 函数,包括在许多现代系统平台上当 close_fdsTrue (默认值) 的时候。 当在 FreeBSD 和 Solaris 上启动进程时这应该能提供显著的性能提升。 请参阅上面的 subprocess 小节了解详情。 (由 Jakub Kulik 在 gh-113117 中贡献。)

被移除的模块与 API

PEP 594: 从标准库中移除“死电池”

PEP 594 提议从标准库移除 19 个模块,它们因其古旧、过时或不安全的状态而被非正式地称呼为‘死电池’。 下列所有模块在 Python 3.11 中被弃用,现在已被移除:

  • aifc

  • audioop

  • chunk

  • cgicgitb

    • 对于 GETHEAD 请求 cgi.FieldStorage 通常可以用 urllib.parse.parse_qsl() 来替换,而对于 POSTPUT 请求则可以用 email.message 模块或 multipart 库。

    • cgi.parse() 可被替换为在想要的查询字符串上直接调用 urllib.parse.parse_qs(),除非输入为 multipart/form-data,它应当如下文针对 cgi.parse_multipart() 所描述的那样被替换。

    • cgi.parse_header() 可被 email 包中的功能所替换,它实现了相同的 MIME RFC。 例如,使用 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 上的 pynntp 库。

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

  • pipes: 改用 subprocess 模块。

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

  • spwd: 改用 PyPI 上的 python-pam 库。

  • sunau

  • telnetlib,改用 PyPI 上的 telnetlib3Exscript 库。

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

  • xdrlib

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

2to3

  • 移除 2to3 程序和 lib2to3 模块,此前已在 Python 3.11 中被弃用。 (由 Victor Stinner 在 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.)

  • Raise a RuntimeError when calling frame.clear() on a suspended frame (as has always been the case for an executing frame). (Contributed by Irit Katriel in gh-79932.)

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

  • 移除了使用 Path 对象作为上下文管理器的能力。 此功能自 Python 3.9 起已被弃用并设为空操作。 (由 Barney Gale 在 gh-83863 中贡献。)

re

  • 移除了未被写入文档、已被弃用且已不能工作的 re.template() 函数和 re.TEMPLATE / re.T 旗标。 (由 Serhiy Storchaka 和 Nikita Sobolev 在 gh-105687 中贡献。)

tkinter.tix

  • 移除了 tkinter.tix 模块,它在 Python 3.6 中已被弃用。 该模块所包装的第三方库 Tix 已不再维护。 (由 Zachary Ware 在 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.)

  • 移除了创建 TypedDict 类型的关键字参数方法,它在 Python 3.11 中已被弃用。 (由 Tomas Roun 在 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.)

新的弃用

  • 用户自定义函数:

    • Deprecate assignment to a function's __code__ attribute, where the new code object's type does not match the function's type. The different types are: plain function, generator, async generator, and coroutine. (Contributed by Irit Katriel in gh-81137.)

  • array:

    • Deprecate the 'u' format code (wchar_t) at runtime. This format code has been deprecated in documentation since Python 3.3, and will be removed in Python 3.16. Use the 'w' format code (Py_UCS4) for Unicode characters instead. (Contributed by Hugo van Kemenade in gh-80480.)

  • ctypes:

    • Deprecate the undocumented SetPointerType() function, to be removed in Python 3.15. (Contributed by Victor Stinner in gh-105733.)

    • Soft-deprecate the ARRAY() function in favour of type * length multiplication. (Contributed by Victor Stinner in gh-105733.)

  • decimal:

    • Deprecate the non-standard and undocumented Decimal format specifier 'N', which is only supported in the decimal module's C implementation. (Contributed by Serhiy Storchaka in gh-89902.)

  • dis:

    • Deprecate the HAVE_ARGUMENT separator. Check membership in hasarg instead. (Contributed by Irit Katriel in gh-109319.)

  • getopt and optparse:

    • Both modules are now soft deprecated, with argparse preferred for new projects. This is a new soft-deprecation for the getopt module, whereas the optparse module was already de facto soft deprecated. (Contributed by Victor Stinner in gh-106535.)

  • gettext:

    • Deprecate non-integer numbers as arguments to functions and methods that consider plural forms in the gettext module, even if no translation was found. (Contributed by Serhiy Storchaka in gh-88434.)

  • glob:

    • Deprecate the undocumented glob0() and glob1() functions. Use glob() and pass a path-like object specifying the root directory to the root_dir parameter instead. (Contributed by Barney Gale in gh-117337.)

  • http.server:

    • Deprecate CGIHTTPRequestHandler, to be removed in Python 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. (Contributed by Gregory P. Smith in gh-109096.)

    • Deprecate the --cgi flag to the python -m http.server command-line interface, to be removed in Python 3.15. (Contributed by Gregory P. Smith in gh-109096.)

  • mimetypes:

  • re:

    • Deprecate passing the optional maxsplit, count, or flags arguments as positional arguments to the module-level split(), sub(), and subn() functions. These parameters will become keyword-only in a future version of Python. (Contributed by Serhiy Storchaka in gh-56166.)

  • pathlib:

  • platform:

    • 弃用了 java_ver(),并将在 Python 3.15 中移除。 此函数仅对 Jython 支持有用,具有令人困惑的 API,并且大部分未经测试。 (由 Nikita Sobolev 在 gh-116349 中贡献。).)

  • pydoc:

    • 弃用未写入文档的 ispackage() 函数。 (由 Zackery Spytz 在 gh-64020 中贡献。)

  • sqlite3:

  • sys:

  • tarfile:

    • 弃用了未写入文档也未被使用的 TarFile.tarfile 属性,并将在 Python 3.16 中移除。 (在 gh-115256 中贡献。)

  • traceback:

  • typing:

    • Deprecate the undocumented keyword argument syntax for creating NamedTuple classes (e.g. Point = NamedTuple("Point", x=int, y=int)), to be removed in Python 3.15. Use the class-based syntax or the functional syntax instead. (Contributed by Alex Waygood in gh-105566.)

    • Deprecate omitting the fields parameter when creating a NamedTuple or typing.TypedDict class, and deprecate passing None to the fields parameter of both types. Python 3.15 will require a valid sequence for the fields parameter. 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.)

    • Deprecate the typing.no_type_check_decorator() decorator function, to be removed in in Python 3.15. After eight years in the typing module, it has yet to be supported by any major type checker. (Contributed by Alex Waygood in gh-106309.)

    • Deprecate typing.AnyStr. In Python 3.16, it will be removed from typing.__all__, and a DeprecationWarning will be emitted at runtime 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.)

  • wave:

计划在 Python 3.14 中移除

Python 3.15 中的待移除功能

  • 导入系统:

    • 当设置 __spec__.cached 失败时在模块上设置 __cached__ 的做法已被弃用。 在 Python 3.15 中,__cached__ 将不会再被导入系统或标准库纳入考虑。 (gh-97879)

    • 当设备 __spec__.parent 失败时在模块上设置 __package__ 的做法已被弃用。 在 Python 3.15 中,__package__ 将不会再被导入系统或标准库纳入考虑。 (gh-97879)

  • ctypes:

    • 未写入文档的 ctypes.SetPointerType() 函数自 Python 3.13 起已被弃用。

  • http.server:

    • 过时且很少被使用的 CGIHTTPRequestHandler 自 Python 3.13 起已被弃用。 不存在直接的替代品。 对于建立带有请求处理器的 Web 服务程序来说 任何东西 都比 CGI 要好。

    • 用于 python -m http.server 命令行界面的 --cgi 旗标自 Python 3.13 起已被弃用。

  • locale:

  • pathlib:

  • platform:

    • java_ver() 自 Python 3.13 起已被弃用。 此函数仅对 Jython 支持有用,具有令人困惑的 API,并且大部分未经测试。

  • threading:

    • 在 Python 3.15 中 RLock() 将不再接受参数。 传入参数的做法自 Python 3.14 起已被弃用,因为 Python 版本不接受任何参数,而 C 版本允许任意数量的位置或关键字参数,但会忽略所有参数。

  • typing:

    • 未写入文档的用于创建 NamedTuple 类的关键字参数语法 (例如 Point = NamedTuple("Point", x=int, y=int)) 自 Python 3.13 起已被弃用。 请改用基于类的语法或函数语法。

    • typing.no_type_check_decorator() 装饰器自 Python 3.13 起已被弃用。 存在于 typing 模块八年之后,它仍未被任何主要类型检查器所支持。

  • wave:

计划在 Python 3.16 中移除

  • builtins:

    • 对布尔类型 ~True~False 执行按位取反的操作自 Python 3.12 起已被弃用,因为它会产生奇怪和不直观的结果 (-2 and -1)。 请改用 not x 来对布尔值执行逻辑否操作。 对于需要对下层整数执行按位取反操作的少数场合,请显式地将其转换为 int (~int(x))。

  • array:

    • 'u' 格式代码 (wchar_t) 自 Python 3.3 起已在文档中弃用并自 Python 3.13 起在运行时弃用。 对于 Unicode 字符请改用 'w' 格式代码 (Py_UCS4)。

  • shutil:

    • ExecError 异常自 Python 3.14 起已被弃用。 它自 Python 3.4 起就未被 shutil 中的任何函数所使用,现在是 RuntimeError 的一个别名。

  • symtable:

  • sys:

  • tarfile:

    • 未写入文档也未被使用的 TarFile.tarfile 属性自 Python 3.13 起被弃用。

计划在未来版本中移除

以下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: warn() 方法自 Python 3.3 起已被弃用,请改用 warning()

  • 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 if the except-depth is 1, which is needed to optimize closing of generators. (Contributed by Irit Katriel in gh-111354.)

C API 的变化

新的特性

被改变的 C API

受限 C API 的改变

Removed C APIs

  • Remove several functions, macros, variables, etc with names prefixed by _Py or _PY (which are considered private). If your project is affected by one of these removals and you believe that the removed API should remain available, please open a new issue to request a public C API and add cc: @vstinner to the issue to notify Victor Stinner. (Contributed by Victor Stinner in gh-106320.)

  • Remove old buffer protocols deprecated in Python 3.0. Use 缓冲协议 instead.

    • PyObject_CheckReadBuffer(): Use PyObject_CheckBuffer() to test whether the object supports the buffer protocol. Note that PyObject_CheckBuffer() doesn't guarantee that PyObject_GetBuffer() will succeed. To test if the object is actually readable, see the next example of PyObject_GetBuffer().

    • PyObject_AsCharBuffer(), PyObject_AsReadBuffer(): Use PyObject_GetBuffer() and PyBuffer_Release() instead:

      Py_buffer view;
      if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) {
          return NULL;
      }
      // Use `view.buf` and `view.len` to read from the buffer.
      // You may need to cast buf as `(const char*)view.buf`.
      PyBuffer_Release(&view);
      
    • PyObject_AsWriteBuffer(): Use PyObject_GetBuffer() and PyBuffer_Release() instead:

      Py_buffer view;
      if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) {
          return NULL;
      }
      // Use `view.buf` and `view.len` to write to the buffer.
      PyBuffer_Release(&view);
      

    (Contributed by Inada Naoki in gh-85275.)

  • 删除了在 Python 3.9 中弃用的各种函数:

    (Contributed by Victor Stinner in gh-105107.)

  • Remove the following old functions to configure the Python initialization, deprecated in Python 3.11:

    Use the new PyConfig API of the Python Initialization Configuration instead (PEP 587), added to Python 3.8. (Contributed by Victor Stinner in gh-105145.)

  • Remove PyEval_AcquireLock() and PyEval_ReleaseLock() functions, deprecated in Python 3.2. They didn't update the current thread state. They can be replaced with:

    (Contributed by Victor Stinner in gh-105182.)

  • 删除了在 Python 3.9 弃用的:c:func:!PyEval_ThreadsInitialized 函数。自Python 3.7 起,Py_Initialize() 总是创建全局解释器锁 :调用:c:func:!PyEval_InitThreads 不做任何事情,而:c:func:!PyEval_ThreadsInitialized 总返回非零值。(由 Victor Stinner 在:gh:105182 中贡献。)

  • Remove the _PyInterpreterState_Get() alias to PyInterpreterState_Get() which was kept for backward compatibility with Python 3.8. The pythoncapi-compat project can be used to get PyInterpreterState_Get() on Python 3.8 and older. (Contributed by Victor Stinner in gh-106320.)

  • Remove the private _PyObject_FastCall() function: use PyObject_Vectorcall() which is available since Python 3.8 (PEP 590). (Contributed by Victor Stinner in gh-106023.)

  • Remove the cpython/pytime.h header file, which only contained private functions. (Contributed by Victor Stinner in gh-106316.)

  • Remove the undocumented PY_TIMEOUT_MAX constant from the limited C API. (Contributed by Victor Stinner in gh-110014.)

  • Remove the old trashcan macros Py_TRASHCAN_SAFE_BEGIN and Py_TRASHCAN_SAFE_END. Replace both with the new macros Py_TRASHCAN_BEGIN and Py_TRASHCAN_END. (Contributed by Irit Katriel in gh-105111.)

已弃用的 C API

计划在 Python 3.14 中移除

Python 3.15 中的待移除功能

计划在未来版本中移除

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

构建变化

  • arm64-apple-ios and arm64-apple-ios-simulator are both now PEP 11 tier 3 platforms. (PEP 730 written and implementation contributed by Russell Keith-Magee in gh-114099.)

  • aarch64-linux-android and x86_64-linux-android are both now PEP 11 tier 3 platforms. (PEP 738 written and implementation contributed by Malcolm Smith in gh-116622.)

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

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

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

  • Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate the configure script. (Contributed by Christian Heimes in gh-89886 and by Victor Stinner in gh-112090.)

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

  • CPython now bundles the mimalloc library by default. 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.)

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

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

  • 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.

  • 现在 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 中贡献。)

Porting to Python 3.13

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

Python API 的变化

  • PEP 667 introduces several changes to the semantics of locals() and f_locals:

    • 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 behavior 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.)

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

  • 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.

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

  • 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. Add a trailing slash to keep the previous behavior and only match directories.

  • The threading module now expects the _thread module to have an _is_main_interpreter() function. This function takes no arguments and returns True if the current interpreter is the main interpreter.

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

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.)

  • PEP 667 introduces several changes to frame-related functions:

    • 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.

    • 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.

    • 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.

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

回归测试的变化

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