Python 3.14 有什么新变化

编者:

Adam Turner 和 Hugo van Kemenade

本文介绍了 Python 3.14 相比 3.13 增加的新特性。 Python 3.14 发布于 2025 年 10 月 7 日。 要了解详细信息,请参阅 更新日志

参见

PEP 745 -- Python 3.14 发布计划

摘要 -- 发布重点

Python 3.14 是 Python 编程语言的最新稳定发布版,包含多项针对语言、实现和标准库的改变。 最大的变化包括 模板字符串字面值, 标注的迟延求值,以及在标准库中对 子解释器 的支持。

标准库的变化包括大幅改进 在 asyncio 中的内省 的功能,新增 compression.zstd 模块以 支持 Zstandard,REPL 中的语法高亮,还有用户友好度和正确性方面的改进。

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


解释器的改进:

标准库中的重大改进:

C API 的改进:

平台支持:

发布包的变更:

新的特性

PEP 649 & PEP 749: 标注的迟延求值

在函数、类和模块上的 标注 将不再被立即求值。 相反,标注会被存储在专门的 标注函数 中并仅在必要时进行求值 (除非使用了 from __future__ import annotations)。

这一改进旨在使得 Python 中的标注在大多数情况下具有更好的性能和可用性。 定义标注的运行时开销被最小化,但仍可在运行时对标注进行内省。 当标注包含前向引用时也不再需要将其包裹在字符串中。

新引入的 annotationlib 模块提供了检查延迟注解的工具。注解可以通过以下格式进行求值:VALUE 格式(将注解求值为运行时值,类似于早期Python版本的行为)、FORWARDREF 格式(用特殊标记替换未定义名称)、STRING 格式(以字符串形式返回注解)。

以下示例展示了这些格式的具体行为:

>>> from annotationlib import get_annotations, Format
>>> def func(arg: Undefined):
...     pass
>>> get_annotations(func, format=Format.VALUE)
Traceback (most recent call last):
  ...
NameError: name 'Undefined' is not defined
>>> get_annotations(func, format=Format.FORWARDREF)
{'arg': ForwardRef('Undefined', owner=<function func at 0x...>)}
>>> get_annotations(func, format=Format.STRING)
{'arg': 'Undefined'}

移植 一节包含了有关因这些改变而可能需要的修改指导,不过大大部分情况下,原来的代码将可继续工作。

(由 Jelle Zijlstra 在 PEP 749gh-119180 中贡献;PEP 649 由 Larry Hastings 编写。)

参见

PEP 649

使用描述器进行标注的迟延求值

PEP 749

实现 PEP 649

PEP 734: 标准库中的多解释器

CPython 运行时支持在同一个进程中同时运行多个 Python 的副本并且已经这样做了 20 多年。 每个这样的副本被称为‘解释器’。 不过,该特性过去只能通过 C-API 来使用。.

由于新增的 concurrent.interpreters 模块,此限制已在 Python 3.14 中被移除。

至少有两个重要理由能说明为何使用多解释器可以带来显著的益处:

  • 它们支持(对 Python 来说)全新的、用户友好的并发模型

  • 真正的多核心并行

For some use cases, concurrency in software improves efficiency and can simplify design, at a high level. At the same time, implementing and maintaining all but the simplest concurrency is often a struggle for the human brain. That especially applies to plain threads (for example, threading), where all memory is shared between all threads.

With multiple isolated interpreters, you can take advantage of a class of concurrency models, like Communicating Sequential Processes (CSP) or the actor model, that have found success in other programming languages, like Smalltalk, Erlang, Haskell, and Go. Think of multiple interpreters as threads but with opt-in sharing.

关于多核并行:从 Python 3.12 开始,各个解释器彼此已实现足够的隔离从而可以并行使用 (参见 PEP 684)。 这使得 Python 能够解锁许多曾经受限于 GIL 的 CPU 密集型应用场景。

使用多个解释器在许多方面与 multiprocessing 类似,因为它们都提供了相互隔离的逻辑“进程”,在默认情况下不共享资源并可并行运行。 然而,在使用多个解释器时,应用程序将使用更少的系统资源并具有更高的运行效率(因为它们仍处于同一个进程内)。 可以将多个解释器视为即具有进程级别的隔离性又具有线程级别的高效率。

While the feature has been around for decades, multiple interpreters have not been used widely, due to low awareness and the lack of a standard library module. Consequently, they currently have several notable limitations, which are expected to improve significantly now that the feature is going mainstream.

当前限制:

  • 启动每个解释器尚未经过优化。

  • 每个解释器会占用超出实际需要的内存(正在持续努力实现解释器之间充分的内部共享)

  • 解释器之间真正实现对象或其他数据共享的选项还很有限(除了 memoryview)。

  • PyPI 上的许多第三方扩展模块尚未与多解释器实现兼容(所有标准库扩展模块 已经 兼容)

  • 目前,针对使用多个隔离解释器编写应用程序的方法,对大多数 Python 用户来说仍较为陌生。

这些限制的影响将取决于未来 CPython 的改进、解释器的使用方式,以及社区通过 PyPI 软件包能解决哪些问题。 根据具体应用场景,这些限制可能并不会有太大影响,因此不妨尝试一下!

此外,未来的 CPython 发布版将进一步减少甚至消除这种开销并提供一些不太适合放到 PyPI 上的工具,大多数限制也可以通过扩展模块来解决,这意味着 PyPI 包可以为 3.14 填补各种功能缺口,甚至能上溯到 3.12 即解释器最终实现真正的隔离并停止共享 GIL 的时候。 同样地,预计在 PyPI 上将产生基于多解释器的高层级抽象库。

关于扩展模块,已在推进一些 PyPI 项目的更新,还有如 Cython, pybind11, nanobind 和 PyO3 这样的工具。 有关隔离扩展模块的具体步骤可参看 隔离扩展模块。 隔离模块与支持 自由线程 所需的工作有大量重叠,因此社区在该领域的持续努力将有助于加快对多解释器的支持进程。

在 3.14 中还增加了:concurrent.futures.InterpreterPoolExecutor

(由 Eric Snow 在 gh-134939 中贡献。)

参见

PEP 734

PEP 750: 模板字符串字面值

模板字符串是一种用于定制字符串处理的新机制。 它们共享与 f-字符串类似的语法,但与 f-字符串不同,它们返回一个代表字符串的静态和插值部分的对象,而不是简单的 str

要编写 t-字符串,应使用 't' 前缀而不是 'f':

>>> variety = 'Stilton'
>>> template = t'Try some {variety} cheese!'
>>> type(template)
<class 'string.templatelib.Template'>

Template 对象在字符串的静态和插值(以花括号标示)在被组合 之前 提供对它们的访问。 迭代 Template 实例可以按顺序访问其的各个部分:

>>> list(template)
['Try some ', Interpolation('Stilton', 'variety', None, ''), ' cheese!']

编写(或调用)代码对 Template 实例进行处理是很容易的。 例如,下面的函数可将静态部分转为小写而将 Interpolation 实例转为大写:

from string.templatelib import Interpolation

def lower_upper(template):
    """Render static parts lowercase and interpolations uppercase."""
    parts = []
    for part in template:
        if isinstance(part, Interpolation):
            parts.append(str(part.value).upper())
        else:
            parts.append(part.lower())
    return ''.join(parts)

name = 'Wenslydale'
template = t'Mister {name}'
assert lower_upper(template) == 'mister WENSLYDALE'

因为 Template 实例会在运行时区分静态和插值部分,它们在无害化用户输入时将很有用处。 这里给读者留一个编写对用户输入的 HTML 进行转义的 html() 函数的作业! 模板处理代码可以提供更高的灵活性。 举例来说,进阶版 html() 函数可以直接在模板中接受一个 HTML 属性的 dict:

attributes = {'src': 'limburger.jpg', 'alt': 'lovely cheese'}
template = t'<img {attributes}>'
assert html(template) == '<img src="limburger.jpg" alt="lovely cheese" />'

当然,模板处理代码不一定要返回字符串结果。 一个 更为 进阶的 html() 可以返回一个代表类似 DOM 结构的自定义类型。

有了 t-字符串,开发者可以编写专用系统来无害化 SQL,执行安全的 shell 操作,改进日志记录,处理 Web 开发中的现代概念(HTML, CSS 等等),以及实现轻量级的自定义业务 DSL。

(由 Jim Baker、Guido van Rossum、Paul Everitt、Koudai Aono、Lysandros Nikolaou、Dave Peck、Adam Turner、Jelle Zijlstra、Bénédikt Tran 和 Pablo Galindo Salgado 在 gh-132661 中贡献。)

参见

PEP 750

PEP 768: 安全的外部调试器接口

Python 3.14 introduces a zero-overhead debugging interface that allows debuggers and profilers to safely attach to running Python processes without stopping or restarting them. This is a significant enhancement to Python's debugging capabilities, meaning that unsafe alternatives are no longer required.

The new interface provides safe execution points for attaching debugger code without modifying the interpreter's normal execution path or adding any overhead at runtime. Due to this, tools can now inspect and interact with Python applications in real-time, which is a crucial capability for high-availability systems and production environments.

For convenience, this interface is implemented in the sys.remote_exec() function. For example:

import sys
from tempfile import NamedTemporaryFile

with NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
    script_path = f.name
    f.write(f'import my_debugger; my_debugger.connect({os.getpid()})')

# Execute in process with PID 1234
print('Behold! An offering:')
sys.remote_exec(1234, script_path)

此函数允许发送 Python 代码以便在目标进程中的下一个安全执行点上执行。 不过,工具作者也可以直接实现在 PEP 中描述的协议,它详细讲解了用于安全附加到运行进程的底层机制。

该调试接口在设计时已充分考虑安全性,并包含多种访问控制机制:

(由 Pablo Galindo Salgado,Matt Wozniski 和 Ivona Stojanovic 在 gh-131591 中贡献)

参见

PEP 768

一种新型的解释器

A new type of interpreter has been added to CPython. It uses tail calls between small C functions that implement individual Python opcodes, rather than one large C case statement. For certain newer compilers, this interpreter provides significantly better performance. Preliminary benchmarks suggest a geometric mean of 3-5% faster on the standard pyperformance benchmark suite, depending on platform and architecture. The baseline is Python 3.14 built with Clang 19, without this new interpreter.

This interpreter currently only works with Clang 19 and newer on x86-64 and AArch64 architectures. However, a future release of GCC is expected to support this as well.

This feature is opt-in for now. Enabling profile-guided optimization is highly recommendeded when using the new interpreter as it is the only configuration that has been tested and validated for improved performance. For further information, see --with-tail-call-interp.

备注

这不应与Python函数的 尾调用优化 相混淆,该特性目前在CPython中尚未实现。

这一新型解释器属于CPython解释器的内部实现细节,完全不会改变Python程序的可见行为。它能提升程序性能,但不会引发任何其他变更。

(由 Ken Jin 在 gh-128563 中贡献,CPython实现方案融合了Mark Shannon、Garrett Gu、Haoran Xu和Josh Haberman的设计理念。)

自由线程模式的改进

CPython's free-threaded mode (PEP 703), initially added in 3.13, has been significantly improved in Python 3.14. The implementation described in PEP 703 has been finished, including C API changes, and temporary workarounds in the interpreter were replaced with more permanent solutions. The specializing adaptive interpreter (PEP 659) is now enabled in free-threaded mode, which along with many other optimizations greatly improves its performance. The performance penalty on single-threaded code in free-threaded mode is now roughly 5-10%, depending on the platform and C compiler used.

From Python 3.14, when compiling extension modules for the free-threaded build of CPython on Windows, the preprocessor variable Py_GIL_DISABLED now needs to be specified by the build backend, as it will no longer be determined automatically by the C compiler. For a running interpreter, the setting that was used at compile time can be found using sysconfig.get_config_var().

The new -X context_aware_warnings flag controls if concurrent safe warnings control is enabled. The flag defaults to true for the free-threaded build and false for the GIL-enabled build.

A new thread_inherit_context flag has been added, which if enabled means that threads created with threading.Thread start with a copy of the Context() of the caller of start(). Most significantly, this makes the warning filtering context established by catch_warnings be "inherited" by threads (or asyncio tasks) started within that context. It also affects other modules that use context variables, such as the decimal context manager. This flag defaults to true for the free-threaded build and false for the GIL-enabled build.

(Contributed by Sam Gross, Matt Page, Neil Schemenauer, Thomas Wouters, Donghee Na, Kirill Podoprigora, Ken Jin, Itamar Oren, Brett Simmers, Dino Viehland, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, Kumar Aditya, Edgar Margffoy, and many others. Some of these contributors are employed by Meta, which has continued to provide significant engineering resources to support this project.)

改进的错误消息

  • 解释器现在能在检测到Python关键字拼写错误时提供有用的建议。当遇到与Python关键字高度相似的单词时,解释器将在错误信息中建议正确的关键字。该功能可帮助程序员快速识别和修复常见的输入错误。例如:

    >>> whille True:
    ...     pass
    Traceback (most recent call last):
      File "<stdin>", line 1
        whille True:
        ^^^^^^
    SyntaxError: invalid syntax. Did you mean 'while'?
    

    虽然该功能主要针对最常见的拼写错误情况,但某些变体的拼写错误仍可能导致常规语法错误。(由 Pablo Galindo 在 gh-132449 中贡献。)

  • 跟在 else 块后的 elif 语句现在会触发特定的错误提示。(由 Steele Farnsworth 在 gh-129902 中贡献。)

    >>> if who == "me":
    ...     print("It's me!")
    ... else:
    ...     print("It's not me!")
    ... elif who is None:
    ...     print("Who is it?")
    File "<stdin>", line 5
      elif who is None:
      ^^^^
    SyntaxError: 'elif' block follows an 'else' block
    
  • If a statement is passed to the 条件表达式 after else, or one of pass, break, or continue is passed before if, then the error message highlights where the expression is required. (Contributed by Sergey Miryanov in gh-129515.)

    >>> x = 1 if True else pass
    Traceback (most recent call last):
      File "<string>", line 1
        x = 1 if True else pass
                           ^^^^
    SyntaxError: expected expression after 'else', but statement is given
    
    >>> x = continue if True else break
    Traceback (most recent call last):
      File "<string>", line 1
        x = continue if True else break
            ^^^^^^^^
    SyntaxError: expected expression before 'if', but statement is given
    
  • 当检测到未正确闭合的字符串时,错误消息会提示该字符串可能是字符串的一部分。(由 Pablo Galindo 在 gh-88535 中贡献。)

    >>> "The interesting object "The important object" is very important"
    Traceback (most recent call last):
    SyntaxError: invalid syntax. Is this intended to be part of the string?
    
  • 当字符串前缀不兼容时,错误提示现在会明确显示哪些前缀存在冲突。(由 Nikita Sobolev 在 gh-133197 中贡献。)

    >>> ub'abc'
      File "<python-input-0>", line 1
        ub'abc'
        ^^
    SyntaxError: 'u' and 'b' prefixes are incompatible
    
  • 在以下场景中使用不兼容目标的 as 语句时,错误提示已得到改进:

    • 导入:import ... as ...

    • From 导入:from ... import ... as ...

    • Except 处理器:except ... as ...

    • 模式匹配 case 语句:case ... as ...

    (由 Nikita Sobolev 在 gh-123539gh-123562gh-123440 中贡献。)

  • 尝试向 dictset 添加不可哈希类型的实例时,错误提示信息已改进。(由 CF Bolz-Tereick 和 Victor Stinner 在 gh-132828 中贡献。)

    >>> s = set()
    >>> s.add({'pages': 12, 'grade': 'A'})
    Traceback (most recent call last):
      File "<python-input-1>", line 1, in <module>
        s.add({'pages': 12, 'grade': 'A'})
        ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: cannot use 'dict' as a set element (unhashable type: 'dict')
    >>> d = {}
    >>> l = [1, 2, 3]
    >>> d[l] = 12
    Traceback (most recent call last):
      File "<python-input-4>", line 1, in <module>
        d[l] = 12
        ~^^^
    TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
    
  • 当使用 async with 而非 with 进入支持同步上下文管理器协议的对象时,错误提示信息已改进。反之,对于异步上下文管理器协议的情况也做了相应优化。(由 Bénédikt Tran 在 gh-128398 中贡献。)

PEP 784: Zstandard support in the standard library

The new compression package contains modules compression.lzma, compression.bz2, compression.gzip and compression.zlib which re-export the lzma, bz2, gzip and zlib modules respectively. The new import names under compression are the preferred names for importing these compression modules from Python 3.14. However, the existing modules names have not been deprecated. Any deprecation or removal of the existing compression modules will occur no sooner than five years after the release of 3.14.

新引入的 compression.zstd 模块通过绑定 Meta的zstd库 提供了Zstandard格式的压缩和解压API。Zstandard是一种被广泛采用、高效且快速的压缩格式。除了 compression.zstd 中引入的API外,对Zstandard压缩归档文件的读写支持也已添加到 tarfilezipfileshutil 模块中。

下面是一个使用新模块压缩数据的示例:

from compression import zstd
import math

data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Achieved compression ratio of {ratio}")

可以看出,该API与 lzmabz2 模块的API类似。

(由 Emma Harper Smith、Adam Turner、Gregory P. Smith、Tomas Roun、Victor Stinner 和 Rogdham 在 gh-132983 中贡献。)

参见

PEP 784

asyncio 内省能力

Added a new command-line interface to inspect running Python processes using asynchronous tasks, available via python -m asyncio ps PID or python -m asyncio pstree PID.

The ps subcommand inspects the given process ID (PID) and displays information about currently running asyncio tasks. It outputs a task table: a flat listing of all tasks, their names, their coroutine stacks, and which tasks are awaiting them.

The pstree subcommand fetches the same information, but instead renders a visual async call tree, showing coroutine relationships in a hierarchical format. This command is particularly useful for debugging long-running or stuck asynchronous programs. It can help developers quickly identify where a program is blocked, what tasks are pending, and how coroutines are chained together.

例如给定以下代码:

import asyncio

async def play_track(track):
    await asyncio.sleep(5)
    print(f'🎵 Finished: {track}')

async def play_album(name, tracks):
    async with asyncio.TaskGroup() as tg:
        for track in tracks:
            tg.create_task(play_track(track), name=track)

async def main():
    async with asyncio.TaskGroup() as tg:
        tg.create_task(
          play_album('Sundowning', ['TNDNBTG', 'Levitate']),
          name='Sundowning')
        tg.create_task(
          play_album('TMBTE', ['DYWTYLM', 'Aqua Regia']),
          name='TMBTE')

if __name__ == '__main__':
    asyncio.run(main())

在运行中的进程上执行该新工具将生成如下表格:

python -m asyncio ps 12345

tid        task id              task name            coroutine stack                                    awaiter chain                                      awaiter name    awaiter id
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1935500    0x7fc930c18050       Task-1               TaskGroup._aexit -> TaskGroup.__aexit__ -> main                                                                       0x0
1935500    0x7fc930c18230       Sundowning           TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TaskGroup._aexit -> TaskGroup.__aexit__ -> main    Task-1          0x7fc930c18050
1935500    0x7fc93173fa50       TMBTE                TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TaskGroup._aexit -> TaskGroup.__aexit__ -> main    Task-1          0x7fc930c18050
1935500    0x7fc93173fdf0       TNDNBTG              sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   Sundowning      0x7fc930c18230
1935500    0x7fc930d32510       Levitate             sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   Sundowning      0x7fc930c18230
1935500    0x7fc930d32890       DYWTYLM              sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TMBTE           0x7fc93173fa50
1935500    0x7fc93161ec30       Aqua Regia           sleep -> play                                      TaskGroup._aexit -> TaskGroup.__aexit__ -> album   TMBTE           0x7fc93173fa50

或生成如下树状结构:

python -m asyncio pstree 12345

└── (T) Task-1
    └──  main example.py:13
        └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
            └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                ├── (T) Sundowning
                   └──  album example.py:8
                       └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
                           └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                               ├── (T) TNDNBTG
                                  └──  play example.py:4
                                      └──  sleep Lib/asyncio/tasks.py:702
                               └── (T) Levitate
                                   └──  play example.py:4
                                       └──  sleep Lib/asyncio/tasks.py:702
                └── (T) TMBTE
                    └──  album example.py:8
                        └──  TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
                            └──  TaskGroup._aexit Lib/asyncio/taskgroups.py:121
                                ├── (T) DYWTYLM
                                   └──  play example.py:4
                                       └──  sleep Lib/asyncio/tasks.py:702
                                └── (T) Aqua Regia
                                    └──  play example.py:4
                                        └──  sleep Lib/asyncio/tasks.py:702

当检测到异步等待图中存在循环引用(可能表明存在编程问题)时,该工具将报错并列出阻碍树形结构构建的循环路径:

python -m asyncio pstree 12345

ERROR: await-graph contains cycles - cannot print a tree!

cycle: Task-2  Task-3  Task-2

(由 Pablo Galindo、 Łukasz Langa、 Yury Selivanov 和 Marta Gomez Macias 在 gh-91048 中贡献。)

并发安全的警告控制

The warnings.catch_warnings context manager will now optionally use a context variable for warning filters. This is enabled by setting the context_aware_warnings flag, either with the -X command-line option or an environment variable. This gives predictable warnings control when using catch_warnings combined with multiple threads or asynchronous tasks. The flag defaults to true for the free-threaded build and false for the GIL-enabled build.

(由 Neil Schemenauer 和 Kumar Aditya 在 gh-130010 中贡献。)

其他语言特性修改

  • 现在Windows平台已支持所有Windows代码页作为 ‘cpXXX’ 编解码器使用。(由 Serhiy Storchaka 在 gh-123803 中贡献。)

  • 实现了符合C99以来C标准规范的实数与复数混合运算规则。(由 Sergey B Kirpichev 在 gh-69639 中贡献。)

  • More syntax errors are now detected regardless of optimisation and the -O command-line option. This includes writes to __debug__, incorrect use of await, and asynchronous comprehensions outside asynchronous functions. For example, python -O -c 'assert (__debug__ := 1)' or python -O -c 'assert await 1' now produce SyntaxErrors. (Contributed by Irit Katriel and Jelle Zijlstra in gh-122245 & gh-121637.)

  • 当纯C类型派生子类时,若子类未显式重写相关方法,新建类型的C槽位将不再被替换为封装版本。(由 Tomasz Pytel 在 gh-132284 中贡献。)

内置

命令行与环境

  • 导入时间分析标志现可通过新增的 -X importtime=2 选项追踪已加载('缓存')模块。当导入此类模块时,selfcumulative 时间值将被替换为字符串 cached

    -X importtime 取大于 2 的值被保留供未来使用。

    (由 Noah Kim 和 Adam Turner 在 gh-118655 中贡献。)

  • 命令行选项 -c 现在会在执行前自动对其代码参数进行去缩进处理,该行为与 textwrap.dedent() 函数保持一致。(由 Jon Crall 和 Steven Sun 在 gh-103998 中贡献。)

  • -J 不再是 Jython 的保留标志,目前不具任何特殊含义。(由 Adam Turner 在 gh-133336 中贡献。)

PEP 758: 允许不带圆括号的 exceptexcept* 表达式

The except and except* expressions now allow brackets to be omitted when there are multiple exception types and the as clause is not used. For example:

try:
    connect_to_server()
except TimeoutError, ConnectionRefusedError:
    print('The network has ceased to be!')

(由 Pablo Galindo 和 Brett Cannon 在 PEP 758gh-131831 中贡献。)

PEP 765: finally 代码块中的控制流

编译器在检测到 returnbreakcontinue 语句跳出 finally 代码块时,现在将触发 SyntaxWarning。此项变更遵循 PEP 765 规范。

In situations where this change is inconvenient (such as those where the warnings are redundant due to code linting), the warning filter can be used to turn off all syntax warnings by adding ignore::SyntaxWarning as a filter. This can be specified in combination with a filter that converts other warnings to errors (for example, passing -Werror -Wignore::SyntaxWarning as CLI options, or setting PYTHONWARNINGS=error,ignore::SyntaxWarning).

Note that applying such a filter at runtime using the warnings module will only suppress the warning in code that is compiled after the filter is adjusted. Code that is compiled prior to the filter adjustment (for example, when a module is imported) will still emit the syntax warning.

(由 Irit Katriel 在 gh-130080 中贡献。)

增量式垃圾回收

循环垃圾回收器现在采用增量式处理。这意味着对于较大的堆内存,最大暂停时间将减少一个数量级或更多。

现在垃圾回收机制仅包含两个代际:新生代和老年代。当未直接调用 gc.collect() 函数时,垃圾回收器的触发频率会稍有降低。而在调用时,它会回收新生代以及部分老年代对象(即增量回收),而非一次性回收一个或多个完整的代际。

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

  • gc.collect(1):执行一次增量式垃圾回收,而非专门回收第1代对象。

  • gc.collect() 的其他调用保持不变。

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

默认的交互式 shell

  • 默认的 interactive shell 现已支持 Python 语法高亮。 此特性默认启用,除非设置了 PYTHON_BASIC_REPL 或任何其他禁用颜色的环境变量。 请参阅 控制颜色 了解详情。

    The default color theme for syntax highlighting strives for good contrast and exclusively uses the 4-bit VGA standard ANSI color codes for maximum compatibility. The theme can be customized using an experimental API _colorize.set_theme(). This can be called interactively or in the PYTHONSTARTUP script. Note that this function has no stability guarantees, and may change or be removed.

    (由 Łukasz Langa 在 gh-131507 中贡献。)

  • The default interactive shell now supports import auto-completion. This means that typing import co and pressing <Tab> will suggest modules starting with co. Similarly, typing from concurrent import i will suggest submodules of concurrent starting with i. Note that autocompletion of module attributes is not currently supported. (Contributed by Tomas Roun in gh-69605.)

新增模块

  • annotationlib: For introspecting annotations. See PEP 749 for more details. (Contributed by Jelle Zijlstra in gh-119180.)

  • compression (including compression.zstd): A package for compression-related modules, including a new module to support the Zstandard compression format. See PEP 784 for more details. (Contributed by Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun, Victor Stinner, and Rogdham in gh-132983.)

  • concurrent.interpreters: Support for multiple interpreters in the standard library. See PEP 734 for more details. (Contributed by Eric Snow in gh-134939.)

  • string.templatelib: Support for template string literals (t-strings). See PEP 750 for more details. (Contributed by Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono, Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran, and Pablo Galindo Salgado in gh-132661.)

改进的模块

argparse

  • argparse.ArgumentParser程序名称 默认值现在会反映 Python 解释器定位 __main__ 模块代码的方式。(由 Serhiy Storchaka 和 Alyssa Coghlan 在 gh-66436 中贡献。)

  • argparse.ArgumentParser 新增可选形参 suggest_on_error,可在用户输入错误时提供参数选项及子解析器名称的建议。(由 Savannah Ostrowski 在 gh-124456 中贡献。)

  • 为帮助文本启用颜色显示,你可以通过向 argparse.ArgumentParser 传递可选的 color 形参来禁用此功能。此外,该功能还可以通过 环境变量 进行控制。(由 Hugo van Kemenade 在 gh-130645 中贡献。)

ast(抽象语法树)

  • Add compare(), a function for comparing two ASTs. (Contributed by Batuhan Taskaya and Jeremy Hylton in gh-60191.)

  • 新增对AST节点 copy.replace() 操作的支持。(由 Bénédikt Tran 在 gh-121141 中贡献。)

  • 在优化级别为2时,文档字符串现会从优化后的AST中移除。(由 Irit Katriel 在 gh-123958 中贡献。)

  • The repr() output for AST nodes now includes more information. (Contributed by Tomas Roun in gh-116022.)

  • When called with an AST as input, the parse() function now always verifies that the root node type is appropriate. (Contributed by Irit Katriel in gh-130139.)

  • Add new options to the command-line interface: --feature-version, --optimize, and --show-empty. (Contributed by Semyon Moroz in gh-133367.)

asyncio

calendar(日历)

  • 默认情况下,calendar 模块的 命令行 文本输出会以彩色高亮显示当日日期,该功能可通过 环境变量 控制。(由 Hugo van Kemenade 在 gh-128317 中贡献。)

concurrent.futures

  • Add a new executor class, InterpreterPoolExecutor, which exposes multiple Python interpreters in the same process ('subinterpreters') to Python code. This uses a pool of independent Python interpreters to execute calls asynchronously.

    This is separate from the new interpreters module introduced by PEP 734. (Contributed by Eric Snow in gh-124548.)

  • On Unix platforms other than macOS, 'forkserver' is now the the default start method for ProcessPoolExecutor (replacing 'fork'). This change does not affect Windows or macOS, where 'spawn' remains the default start method.

    如需使用与线程不兼容的 fork 启动方法,必须通过向 ProcessPoolExecutor 提供 mp_context 多进程上下文参数来显式指定。

    请参阅 forkserver 限制说明 了解与 fork 方法的差异信息,以及此项变更对存在以下情况的现有代码可能产生的影响:(1) 使用可变全局共享变量 (2) 包含无法被 pickle 自动序列化的共享对象。

    (由 Gregory P. Smith 在 gh-84559 中贡献)

  • Add two new methods to ProcessPoolExecutor, terminate_workers() and kill_workers(), as ways to terminate or kill all living worker processes in the given pool. (Contributed by Charles Machalow in gh-130849.)

  • Add the optional buffersize parameter to Executor.map to limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterables pauses until a result is yielded from the buffer. (Contributed by Enzo Bonnal and Josh Rosenberg in gh-74028.)

configparser

  • configparser will no longer write config files it cannot read, to improve security. Attempting to write() keys containing delimiters or beginning with the section header pattern will raise an InvalidWriteError. (Contributed by Jacob Lincoln in gh-129270.)

contextvars

ctypes

  • The layout of bit fields in Structure and Union objects is now a closer match to platform defaults (GCC/Clang or MSVC). In particular, fields no longer overlap. (Contributed by Matthias Görgens in gh-97702.)

  • 现在可通过设置 Structure._layout_ 类属性来匹配非默认ABI。(由 Petr Viktorin 在 gh-97702 中贡献。)

  • Structure/Union 的字段描述符类现以 CField 形式提供,并新增了辅助调试和内省的属性。(由 Petr Viktorin 在 gh-128715 中贡献。)

  • 在Windows平台上,COMError 异常现已公开。(由 Jun Komoda 在 gh-126686 中贡献。)

  • 在Windows平台上,CopyComPointer() 函数现已公开。(由 Jun Komoda 在 gh-127275 中贡献。)

  • Add memoryview_at(), a function to create a memoryview object that refers to the supplied pointer and length. This works like ctypes.string_at() except it avoids a buffer copy, and is typically useful when implementing pure Python callback functions that are passed dynamically-sized buffers. (Contributed by Rian Hunter in gh-112018.)

  • Complex types, c_float_complex, c_double_complex, and c_longdouble_complex, are now available if both the compiler and the libffi library support complex C types. (Contributed by Sergey B Kirpichev in gh-61103.)

  • 新增 ctypes.util.dllist() 函数,用于列出当前进程已加载的共享库。(由 Brian Ward 在 gh-119349 中贡献。)

  • Move ctypes.POINTER() types cache from a global internal cache (_pointer_type_cache) to the _CData.__pointer_type__ attribute of the corresponding ctypes types. This will stop the cache from growing without limits in some situations. (Contributed by Sergey Miryanov in gh-100926.)

  • 现在 py_object 类型已支持下标,使其成为 generic type。 (由 Brian Schubert 在 gh-132168 中贡献。)

  • 现在 ctypes 已支持 自由线程构建版。 (由 Kumar Aditya 和 Peter Bierma 在 gh-127945 中贡献。)

curses

datetime

decimal

difflib

  • Comparison pages with highlighted changes generated by the HtmlDiff class now support 'dark mode'. (Contributed by Jiahao Li in gh-129939.)

dis

errno

faulthandler

fnmatch

  • Add filterfalse(), a function to reject names matching a given pattern. (Contributed by Bénédikt Tran in gh-74598.)

fractions

functools

getopt

  • 新增对可选参数选项的支持。(由 Serhiy Storchaka 在 gh-126374 中贡献。)

  • 新增对按顺序返回混合选项和非选项参数的支持。(由 Serhiy Storchaka 在 gh-126390 中贡献。)

getpass

  • Support keyboard feedback in the getpass() function via the keyword-only optional argument echo_char. Placeholder characters are rendered whenever a character is entered, and removed when a character is deleted. (Contributed by Semyon Moroz in gh-77065.)

graphlib

heapq

hmac

  • 新增基于 HACL* 项目形式化验证代码的 HMAC (RFC 2104) 内置实现。当 OpenSSL 的 HMAC 实现不可用时,该实现将作为备用方案。(由 Bénédikt Tran 在 gh-99108 中贡献。)

http

imaplib

inspect

io

json

  • Add exception notes for JSON serialization errors that allow identifying the source of the error. (Contributed by Serhiy Storchaka in gh-122163.)

  • Allow using the json module as a script using the -m switch: python -m json. This is now preferred to python -m json.tool, which is soft deprecated. See the JSON command-line interface documentation. (Contributed by Trey Hunner in gh-122873.)

  • 默认情况下,JSON 命令行界面 的输出会以彩色突出显示。这可以通过 环境变量 进行控制。(由 Tomas Roun 在 gh-131952 中贡献。)

linecache

  • getline() can now retrieve source code for frozen modules. (Contributed by Tian Gao in gh-131638.)

logging.handlers

math

  • 为模块中的域错误添加了更详细的错误消息。(由 Charlie Zhao 和 Sergey B Kirpichev 在 gh-101410 中贡献。)

mimetypes

  • Add a public command-line for the module, invoked via python -m mimetypes. (Contributed by Oleg Iarygin and Hugo van Kemenade in gh-93096.)

  • 增加了一些基于 RFC 和通常用例的新 MIME 类型:

    用于字体的 Microsoft 和 RFC 8081 MIME 类型

    • 嵌入式 OpenType: application/vnd.ms-fontobject

    • OpenType 布局(OTF) font/otf

    • TrueType: font/ttf

    • WOFF 1.0 font/woff

    • WOFF 2.0 font/woff2

    用于 Matroska 音视频数据容器结构的 RFC 9559 MIME 类型

    • 仅有音频,无视频: audio/matroska (.mka)

    • 视频:video/matroska (.mkv)

    • 立体视频: video/matroska-3d (.mk3d)

    基于 RFC 的图像

    • RFC 1494: CCITT Group 3 (.g3)

    • RFC 3362: Real-time Facsimile, T.38 (.t38)

    • RFC 3745: JPEG 2000 (.jp2)、扩展格式 (.jpx) 和复合格式 (.jpm)

    • RFC 3950: 标签图像文件格式传真扩展,TIFF-FX (.tfx)

    • RFC 4047: 灵活图像传输系统 (.fits)

    • RFC 7903: 增强型图元文件 (.emf) 和 Windows 图元文件 (.wmf)

    其他 MIME 类型的增加和改变

    • RFC 2361: 将 .avi 的类型更改为 video/vnd.avi,将 .wav 的类型更改为 audio/vnd.wave

    • RFC 4337:添加 MPEG-4 audio/mp4 (.m4a)

    • RFC 5334:添加 Ogg 媒体(.oga.ogg.ogx

    • RFC 6713:添加 application/gzip (.gz)

    • RFC 9639: 添加 FLAC 格式的 audio/flac (.flac)

    • RFC 9512 application/yaml MIME type for YAML files (.yaml and .yml)

    • 添加 7z application/x-7z-compressed (.7z)

    • 非严格模式下,添加Android安装包 application/vnd.android.package-archive (.apk)

    • 添加 deb application/x-debian-package (.deb)

    • 添加 glTF 二进制格式 model/gltf-binary (.glb)

    • 添加glTF JSON/ASCII格式 model/gltf+json (.gltf)

    • 添加 M4V video/x-m4v (.m4v)

    • 添加 PHP application/x-httpd-php (.php)

    • 添加 RAR application/vnd.rar (.rar)

    • 添加 RPM application/x-rpm (.rpm)

    • 添加STL格式 model/stl (.stl)

    • 添加 Windows 媒体视频 video/x-ms-wmv (.wmv)

    • 事实上:添加WebM格式 audio/webm (.weba)

    • ECMA-376: 添加 .docx.pptx.xlsx 类型

    • OASIS: 添加 OpenDocument 格式的 .odg.odp.ods.odt 类型

    • W3C: 添加 EPUB 格式的 application/epub+zip (.epub)

    (Contributed by Sahil Prajapati and Hugo van Kemenade in gh-84852, by Sasha "Nelie" Chernykh and Hugo van Kemenade in gh-132056, and by Hugo van Kemenade in gh-89416, gh-85957, and gh-129965.)

multiprocessing

  • On Unix platforms other than macOS, 'forkserver' is now the the default start method (replacing 'fork'). This change does not affect Windows or macOS, where 'spawn' remains the default start method.

    If the threading incompatible fork method is required, you must explicitly request it via a context from get_context() (preferred) or change the default via set_start_method().

    请参阅 forkserver 限制说明 了解与 fork 方法的差异信息,以及此项变更对存在以下情况的现有代码可能产生的影响:(1) 使用可变全局共享变量 (2) 包含无法被 pickle 自动序列化的共享对象。

    (由 Gregory P. Smith 在 gh-84559 中贡献)

  • multiprocessing's 'forkserver' start method now authenticates its control socket to avoid solely relying on filesystem permissions to restrict what other processes could cause the forkserver to spawn workers and run code. (Contributed by Gregory P. Smith for gh-97514.)

  • 针对 listdict 类型的 多进程代理对象 增加了此前被忽略的缺失方法:

    • clear()copy() 用于 list 的代理

    • fromkeys()reversed(d)d | {}{} | dd |= {'b': 2} 用于 dict 的代理

    (由 Roy Hyunjin Han 在 gh-103134 中贡献。)

  • Add support for shared set objects via SyncManager.set(). The set() in Manager() method is now available. (Contributed by Mingyu Park in gh-129949.)

  • Add the interrupt() to multiprocessing.Process objects, which terminates the child process by sending SIGINT. This enables finally clauses to print a stack trace for the terminated process. (Contributed by Artem Pulkin in gh-131913.)

operator

  • Add is_none() and is_not_none() as a pair of functions, such that operator.is_none(obj) is equivalent to obj is None and operator.is_not_none(obj) is equivalent to obj is not None. (Contributed by Raymond Hettinger and Nico Mexis in gh-115808.)

os

os.path

pathlib

  • pathlib.Path 新增递归复制/移动文件和目录的方法:

    • copy() 将一个文件或目录树复制到目标位置。

    • copy_into() 会将内容复制 目标目录中。

    • move() 将一个文件或目录树移动到目标位置。

    • move_into() 会将内容移动 目标目录中。

    (由 Barney Gale 在 gh-73991 中贡献。)

  • Add the info attribute, which stores an object implementing the new pathlib.types.PathInfo protocol. The object supports querying the file type and internally caching stat() results. Path objects generated by iterdir() are initialized with file type information gleaned from scanning the parent directory. (Contributed by Barney Gale in gh-125413.)

pdb

  • The pdb module now supports remote attaching to a running Python process using a new -p PID command-line option:

    python -m pdb -p 1234
    

    该操作将连接到指定PID的Python进程,并允许您进行交互式调试。请注意,由于Python解释器的工作原理,当附加到阻塞在系统调用或等待I/O的远程进程时,调试功能只有在执行下一条字节码指令或进程收到信号时才会生效。

    This feature uses PEP 768 and the new sys.remote_exec() function to attach to the remote process and send the PDB commands to it.

    (由 Matt Wozniski 和 Pablo Galindo 在 gh-131591 中贡献。)

  • Hardcoded breakpoints (breakpoint() and set_trace()) now reuse the most recent Pdb instance that calls set_trace(), instead of creating a new one each time. As a result, all the instance specific data like display and commands are preserved across hardcoded breakpoints. (Contributed by Tian Gao in gh-121450.)

  • pdb.Pdb 新增一个 mode 参数。当 pdb 处于 inline 模式时,禁用 restart 命令。(由 Tian Gao 在 gh-123757 中贡献。)

  • 当用户尝试在 inline 模式下退出 pdb 时,会显示一个确认提示。输入 yY、按 <Enter>EOF 将确认退出并调用 sys.exit(),而非引发 bdb.BdbQuit。(由 Tian Gao 在 gh-124704 中贡献。)

  • breakpoint()pdb.set_trace() 这样的内联断点将始终在调用帧处暂停程序,而忽略 skip 模式(如果有的话)。(由 Tian Gao 在 gh-130493 中贡献。)

  • pdb 的多行输入中,行首的 <tab> 键现在会填充 4 个空格的缩进,而不是插入 \t 字符。(由 Tian Gao 在 gh-130471 中贡献。)

  • pdb 的多行输入中引入了自动缩进功能。当检测到新的代码块时,它会要么保持上一行的缩进,要么插入 4 个空格的缩进。(由 Tian Gao 在 gh-133350 中贡献。)

  • 新增 $_asynctask 以在适用情况下访问当前的 asyncio 任务。(由 Tian Gao 在 gh-124367 中贡献。)

  • 新增 pdb.set_trace_async() 以支持调试 asyncio 协程。此函数支持 await 语句。(由 Tian Gao 在 gh-132576 中贡献。)

  • Source code displayed in pdb will be syntax-highlighted. This feature can be controlled using the same methods as the default interactive shell, in addition to the newly added colorize argument of pdb.Pdb. (Contributed by Tian Gao and Łukasz Langa in gh-133355.)

pickle

  • pickle 模块的默认协议版本设置为 5。更多详细信息,请参见 pickle protocols

  • Add exception notes for pickle serialization errors that allow identifying the source of the error. (Contributed by Serhiy Storchaka in gh-122213.)

platform

pydoc

  • 帮助输出中的 注解 现在通常以更接近原始源代码中的格式显示。(由 Jelle Zijlstra 在 gh-101552 中贡献。)

re

  • 正则表达式 中,现支持将 \z 作为 \Z 的同义符使用。与行为存在微妙差异的 \Z 不同,\z 在其他多种正则表达式引擎中具有明确无歧义的解析方式。(由 Serhiy Storchaka 在 gh-133306 中贡献。)

  • \B in regular expression now matches the empty input string, meaning that it is now always the opposite of \b. (Contributed by Serhiy Storchaka in gh-124130.)

socket

  • 改进并修复对蓝牙套接字的支持。

    • 修复了 NetBSD 和 DragonFly BSD 系统上对蓝牙套接字的支持。(由 Serhiy Storchaka 在 gh-132429 中贡献。)

    • 修复了 FreeBSD 系统上对 BTPROTO_HCI 的支持。(由 Victor Stinner 在 gh-111178 中贡献。)

    • 新增对 FreeBSD 系统上 BTPROTO_SCO 的支持。(由 Serhiy Storchaka 在 gh-85302 中贡献。)

    • 新增对 FreeBSD 系统上 BTPROTO_L2CAP 地址中 cidbdaddr_type 的支持。(由 Serhiy Storchaka 在 gh-132429 中贡献。)

    • 新增对 Linux 系统上 BTPROTO_HCI 地址中 channel 的支持。(由 Serhiy Storchaka 在 gh-70145 中贡献。)

    • 在 Linux 系统上,允许将整数作为 BTPROTO_HCI 的地址。(由 Serhiy Storchaka 在 gh-132099 中贡献。)

    • BTPROTO_L2CAP 中,getsockname() 会返回 cid。(由 Serhiy Storchaka 在 gh-132429 中贡献。)

    • 新增了许多常量。(由 Serhiy Storchaka 在 gh-132734 中贡献。)

ssl

  • Indicate through the HAS_PHA Boolean whether the ssl module supports TLSv1.3 post-handshake client authentication (PHA). (Contributed by Will Childs-Klein in gh-128036.)

struct

  • struct 模块中支持 float complexdouble complex 这两种 C 类型(分别对应格式字符 'F''D')。(由 Sergey B Kirpichev 在 gh-121249 中贡献。)

symtable

sys

  • The previously undocumented special function sys.getobjects(), which only exists in specialized builds of Python, may now return objects from other interpreters than the one it's called in. (Contributed by Eric Snow in gh-125286.)

  • 新增 sys._is_immortal() 函数,用于判断一个对象是否为 immortal。 (由 Peter Bierma 在 gh-128509 中贡献。)

  • On FreeBSD, sys.platform no longer contains the major version number. It is always 'freebsd', instead of 'freebsd13' or 'freebsd14'. (Contributed by Michael Osipov in gh-129393.)

  • sys._clear_type_cache() 函数引发 DeprecationWarning 警告。该函数在 Python 3.13 中已被弃用,但此前并未引发运行时警告。

  • Add sys.remote_exec() to implement the new external debugger interface. See PEP 768 for details. (Contributed by Pablo Galindo Salgado, Matt Wozniski, and Ivona Stojanovic in gh-131591.)

  • Add the sys._jit namespace, containing utilities for introspecting just-in-time compilation. (Contributed by Brandt Bucher in gh-133231.)

sys.monitoring

sysconfig

tarfile

threading

tkinter

  • Make tkinter widget methods after() and after_idle() accept keyword arguments. (Contributed by Zhikang Yan in gh-126899.)

  • Add ability to specify a name for tkinter.OptionMenu and tkinter.ttk.OptionMenu. (Contributed by Zhikang Yan in gh-130482.)

turtle(海龟绘图)

types(类型)

typing

  • The types.UnionType and typing.Union types are now aliases for each other, meaning that both old-style unions (created with Union[int, str]) and new-style unions (int | str) now create instances of the same runtime type. This unifies the behavior between the two syntaxes, but leads to some differences in behavior that may affect users who introspect types at runtime:

    • Both syntaxes for creating a union now produce the same string representation in repr(). For example, repr(Union[int, str]) is now "int | str" instead of "typing.Union[int, str]".

    • Unions created using the old syntax are no longer cached. Previously, running Union[int, str] multiple times would return the same object (Union[int, str] is Union[int, str] would be True), but now it will return two different objects. Use == to compare unions for equality, not is. New-style unions have never been cached this way. This change could increase memory usage for some programs that use a large number of unions created by subscripting typing.Union. However, several factors offset this cost: unions used in annotations are no longer evaluated by default in Python 3.14 because of PEP 649; an instance of types.UnionType is itself much smaller than the object returned by Union[] was on prior Python versions; and removing the cache also saves some space. It is therefore unlikely that this change will cause a significant increase in memory usage for most users.

    • Previously, old-style unions were implemented using the private class typing._UnionGenericAlias. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers like get_origin() and typing.get_args() instead of relying on private implementation details.

    • 现在可以在 isinstance() 检查中使用 typing.Union 本身。例如,isinstance(int | str, typing.Union) 将返回 True;而此前这会引发 TypeError

    • The __args__ attribute of typing.Union objects is no longer writable.

    • It is no longer possible to set any attributes on Union objects. This only ever worked for dunder attributes on previous versions, was never documented to work, and was subtly broken in many cases.

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

  • TypeAliasType 现在支持星号解包操作。

unicodedata

  • Unicode 数据库已更新到 16.0.0 版本。

unittest

urllib

  • 升级 urllib.request 的 HTTP 摘要认证算法,支持 RFC 7616 中规定的 SHA-256 摘要认证。(由 Calvin Bui 在 gh-128193 中贡献。)

  • 改进解析和生成 file: URL 时的易用性和标准合规性。

    url2pathname() 中:

    • 当新的 require_scheme 参数设为 true 时,接受完整的 URL。

    • 如果 URL 的权限部分与本地主机名匹配,则舍弃该部分。

    • 当新的 resolve_host 参数设为 true 时,若 URL 的权限部分解析为本地 IP 地址,则舍弃该部分。

    • 丢弃 URL 查询和片段组件。

    • 如果 URL 的权限部分不是本地的,则引发 URLError,但在 Windows 系统上,仍会像以前一样返回 UNC 路径。

    pathname2url() 中:

    • 当新的 add_scheme 参数设为 true 时,返回完整的 URL。

    • 当路径以斜杠开头时,包含一个空的 URL 权限部分。例如,路径 /etc/hosts 会被转换为 URL ///etc/hosts

    在 Windows 系统上,盘符不再转换为大写,且非紧跟在驱动器号后的 : 字符不再引发 OSError 异常。

    (由 Barney Gale 在 gh-125866 中贡献。)

uuid

webbrowser

  • BROWSER 环境变量中的名称现在可以引用 webbrowser 模块中已注册的浏览器,而不必总是生成新的浏览器命令。

    这使得可以将 BROWSER 设置为 macOS 上受支持的浏览器之一的值。

zipfile

性能优化

asyncio

  • Standard benchmark results have improved by 10-20% following the implementation of a new per-thread doubly linked list for native tasks, also reducing memory usage. This enables external introspection tools such as python -m asyncio pstree to introspect the call graph of asyncio tasks running in all threads. (Contributed by Kumar Aditya in gh-107803.)

  • 该模块现在对 自由线程构建 提供了一流的支持。这使得多个事件循环可以在不同线程中并行执行,并且随着线程数量的增加线性扩展。(由 Kumar Aditya 在 gh-128002 中贡献。)

base64

  • b16decode() 的速度现在提升了高达六倍。(由 Bénédikt Tran、Chris Markiewicz 和 Adam Turner 在 gh-118761 中贡献。)

bdb

  • 基本调试器现在有了基于 sys.monitoring 的后端,可以通过将 'monitoring' 传递给 Bdb 类的新 backend 参数来选择。(由 Tian Gao 在 gh-124533 中贡献。)

difflib

  • IS_LINE_JUNK() 函数的速度现在提升了一倍。(由 Adam Turner 和 Semyon Moroz 在 gh-130167 中贡献。)

gc

  • 新的 增量垃圾回收器 意味着对于较大的堆,最大暂停时间减少了至少一个数量级。

    由于这种优化,get_threshold()set_threshold() 的结果含义发生了变化,同时还有 get_count()get_stats()

    • 为了向后兼容,get_threshold() 继续返回一个三项元组。第一个值是年轻代回收的阈值,与之前相同;第二个值决定了老年代回收的扫描速率(默认值为10,值越高意味着老年代回收扫描越慢)。第三个值现在没有意义,总是为零。

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

    • get_count()get_stats() 方法仍返回相同格式的结果。唯一的区别在于,结果不再分别对应新生代、老化代和老年代,而是对应新生代以及老年代的待老化空间和回收空间。

    总之,尝试操控循环垃圾回收器行为的代码可能无法完全按预期工作,但几乎不会造成危害。其他所有代码都将正常运行。

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

io

  • 打开和读取文件现在执行更少的系统调用。完整读取一个小型操作系统缓存文件的速度提高了最多15%。(由 Cody Maloney 和 Victor Stinner 在 gh-120754gh-90102 中贡献。)

pathlib

  • Path.read_bytes 现在使用无缓冲模式打开文件,完整读取的速度提高了 9% 到 17%。(由 Cody Maloney 在 gh-120754 中贡献。)

pdb

uuid

  • uuid3()uuid5() 对于16字节名称的速度现在大约提高了40%,对于1024字节名称的速度提高了20%。更长名称的性能保持不变。(由 Bénédikt Tran 在 gh-128150 中贡献。)

  • uuid4() 的速度现在提高了约30%。(由 Bénédikt Tran 在 gh-128150 中贡献。)

zlib

  • 在 Windows 上,zlib-ng 现在用作默认二进制文件中 zlib 模块的实现。已知 zlib-ng 与之前使用的 zlib 实现之间没有不兼容性。这应在所有压缩级别上带来更好的性能。

    值得注意的是,zlib.Z_BEST_SPEED1) 可能会导致比之前的实现显著更低的压缩率,同时显著减少压缩所需的时间。

    (由 Steve Dower 在 gh-91349 中贡献。)

移除

argparse

  • 移除 BooleanOptionalActiontypechoicesmetavar 形参。 它们自 Python 3.12 起已被弃用。 (由 Nikita Sobolev 在 gh-118805 中贡献。)

  • 在参数组上调用 add_argument_group() 现在会引发 ValueError。 类似地,在互斥组上调用 add_argument_group()add_mutually_exclusive_group() 现在都会引发 ValueError。 这种“嵌套调用”从未被支持,经常无法正常工作,且通过继承关系被意外暴露。 该功能自 Python 3.11 起已被弃用。 (由 Savannah Ostrowski 在 gh-127186 中贡献。)

ast(抽象语法树)

  • 移除以下自 Python 3.8 起作为 Constant 的已弃用别名,且自 Python 3.12 起已发出弃用警告的类:

    • Bytes

    • Ellipsis

    • NameConstant

    • Num

    • Str

    由于这些移除操作,当自定义的 NodeVisitor 子类访问抽象语法树(AST)时,用户定义的 visit_Numvisit_Strvisit_Bytesvisit_NameConstantvisit_Ellipsis 方法将不再被调用。请改用定义 visit_Constant 方法。

    (由 Alex Waygood 在 gh-119562 中贡献。)

  • 移除以下 ast.Constant 为兼容现已移除的 AST 类而保留的已弃用属性:

    • Constant.n

    • Constant.s

    改用 Constant.value。 (由 Alex Waygood 在 gh-119562 中贡献。)

asyncio

  • 移除以下自 Python 3.12 起已被弃用的类、方法和函数:

    • AbstractChildWatcher

    • FastChildWatcher

    • MultiLoopChildWatcher

    • PidfdChildWatcher

    • SafeChildWatcher

    • ThreadedChildWatcher

    • AbstractEventLoopPolicy.get_child_watcher()

    • AbstractEventLoopPolicy.set_child_watcher()

    • get_child_watcher()

    • set_child_watcher()

    (由 Kumar Aditya 在 gh-120804 中贡献。)

  • asyncio.get_event_loop() 现在如果没有当前事件循环,会引发 RuntimeError 异常,且不再隐式创建事件循环。

    (由 Kumar Aditya 在 gh-126353 中贡献。)

    当前存在几种使用 asyncio.get_event_loop() 的模式,其中大多数可替换为 asyncio.run()

    如果正在运行异步函数,直接使用 asyncio.run() 即可。

    之前:

    async def main():
        ...
    
    
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(main())
    finally:
        loop.close()
    

    之后:

    async def main():
        ...
    
    asyncio.run(main())
    

    如果需要启动某些持续运行的服务,例如监听套接字的服务器,请使用 asyncio.run() 配合 asyncio.Event 实现。

    之前:

    def start_server(loop): ...
    
    loop = asyncio.get_event_loop()
    try:
        start_server(loop)
        loop.run_forever()
    finally:
        loop.close()
    

    之后:

    def start_server(loop): ...
    
    async def main():
        start_server(asyncio.get_running_loop())
        await asyncio.Event().wait()
    
    asyncio.run(main())
    

    如果需要在事件循环中运行某些任务,同时在其前后执行阻塞代码,请使用 asyncio.Runner

    之前:

    async def operation_one(): ...
    def blocking_code(): ...
    async def operation_two(): ...
    
    loop = asyncio.get_event_loop()
    try:
        loop.run_until_complete(operation_one())
        blocking_code()
        loop.run_until_complete(operation_two())
    finally:
        loop.close()
    

    之后:

    async def operation_one(): ...
    def blocking_code(): ...
    async def operation_two(): ...
    
    with asyncio.Runner() as runner:
        runner.run(operation_one())
        blocking_code()
        runner.run(operation_two())
    

email

  • 移除 email.utils.localtime() 函数的 isdst 形参。该参数自 Python 3.12 起已被弃用且一直被忽略。(由 Hugo van Kemenade 在 gh-118798 中贡献。)

importlib.abc

itertools

  • 移除 itertools 迭代器对复制(copy)、深度复制(deepcopy)和序列化(pickle)操作的支持。自 Python 3.12 起,这些操作已触发 DeprecationWarning 警告。(由 Raymond Hettinger 在 gh-101588 中贡献。)

pathlib

  • 移除向 Path 传递额外关键字参数的支持。在先前版本中,此类参数均会被忽略。(由 Barney Gale 在 gh-74033 中贡献。)

  • 移除向 PurePath.relative_to()is_relative_to() 方法传递额外位置参数的支持。在先前版本中,此类参数会被拼接到 other 参数上。(由 Barney Gale 在 gh-78707 中贡献。)

pkgutil

  • 移除 get_loader()find_loader() 函数,这两个函数自 Python 3.12 起已被弃用。(由 Bénédikt Tran 在 gh-97850 中贡献。)

pty

  • 移除 master_open()slave_open() 函数,这两个函数自 Python 3.12 起已被弃用。请改用 pty.openpty() 函数。

sqlite3

urllib

  • urllib.parse 模块中移除 Quoter 类,该类自 Python 3.11 起已被弃用。(由 Nikita Sobolev 在 gh-118827 中贡献。)

  • urllib.request 模块中移除 URLopenerFancyURLopener 类,这两个类自 Python 3.3 起已被弃用。

    myopener.open() 可以替换为 urlopen()myopener.retrieve() 可以替换为 urlretrieve()。对 opener 类的自定义操作可以通过向 build_opener() 传递定制化的处理程序来实现替换。(由 Barney Gale 在 gh-84850 中贡献。)

弃用

新的弃用

计划在 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:

    • The obsolete and rarely used CGIHTTPRequestHandler has been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler.

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

  • importlib:

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

  • locale:

  • pathlib:

    • .PurePath.is_reserved() has been deprecated since Python 3.13. Use os.path.isreserved() to detect reserved paths on Windows.

  • platform:

    • platform.java_ver() has been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.

  • sysconfig:

  • threading:

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

  • types:

  • typing:

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

    • 当使用 TypedDict 的函数式语法时,不向 fields 形参传递值 (TD = TypedDict("TD")) 或传递 None (TD = TypedDict("TD", None)) 的做法自 Python 3.13 起已被弃用。 请改用 class TD(TypedDict): passTD = TypedDict("TD", {}) 来创建一个零字段的 TypedDict。

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

  • sre_compile, sre_constantssre_parse 模块。

  • wave

    • The getmark(), setmark() and getmarkers() methods of the Wave_read and Wave_write classes have been deprecated since Python 3.13.

  • zipimport:

    • zipimport.zipimporter.load_module() has been deprecated since Python 3.10. Use exec_module() instead. (gh-125746.)

计划在 Python 3.16 中移除

计划在 Python 3.17 中移除

  • collections.abc:

    • collections.abc.ByteString 计划在 Python 3.17 中移除。

      使用 isinstance(obj, collections.abc.Buffer) 来测试 obj 是否在运行时实现了 缓冲区协议。 要用于类型标注,则使用 Buffer 或是显式指明你的代码所支持类型的并集 (例如 bytes | bytearray | memoryview)。

      ByteString 原本是想作为 bytesbytearray 的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是 ByteString 的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如 memoryview 同样不能被当作是 ByteString 的子类型(无论是在运行时还是对于静态类型检查器)。

      请参阅 PEP 688 了解详情。 (由 Shantanu Jain 在 gh-91896 中贡献。)

  • typing:

    • 在 Python 3.14 之前,旧式的联合是通过私有类 typing._UnionGenericAlias 实现的。实现已不再需要该类,但为向后兼容性保留了该类,并计划在 Python 3.17 中删除。 用户应使用记录在案的内省助手函数,如 typing.get_origin()typing.get_args(),而不是依赖于私有的实现细节。

    • typing.ByteString 自 Python 3.9 起已被弃用,计划在 Python 3.17 中移除。

      使用 isinstance(obj, collections.abc.Buffer) 来测试 obj 是否在运行时实现了 缓冲区协议。 要用于类型标注,则使用 Buffer 或是显式指明你的代码所支持类型的并集 (例如 bytes | bytearray | memoryview)。

      ByteString 原本是想作为 bytesbytearray 的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是 ByteString 的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如 memoryview 同样不能被当作是 ByteString 的子类型(无论是在运行时还是对于静态类型检查器)。

      请参阅 PEP 688 了解详情。 (由 Shantanu Jain 在 gh-91896 中贡献。)

计划在 Python 3.19 中移除

  • ctypes:

    • 在非 Windows 平台上,通过设置 _pack_ 而非 _layout_ ,隐式切换到与 MSVC 兼容的结构布局。

  • hashlib:

    • In hash function constructors such as new() or the direct hash-named constructors such as md5() and sha256(), their optional initial data parameter could also be passed a keyword argument named data= or string= in various hashlib implementations.

      Support for the string keyword argument name is now deprecated and slated for removal in Python 3.19.

      Before Python 3.13, the string keyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.

Pending removal in Python 3.20

计划在未来版本中移除

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

  • argparse

    • 嵌套参数组和嵌套互斥组已被弃用 。

    • 将未写入文档的关键字参数 prefix_chars 传递给 add_argument_group() 的做法现在已被弃用。

    • argparse.FileType 类型转换器已弃用 。

  • builtins:

    • 生成器: 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 中贡献。)

  • codecscodecs.open() 请改用 open() 。 (gh-133038)

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

  • datetime:

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

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

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

  • importlib:

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

  • 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

  • threading 的方法:

  • typing.Text (gh-92332)。

  • 内部类 typing._UnionGenericAlias 不再用于实现 typing.Union。为了保护使用该私有类的用户的兼容性 ,将至少在 Python 3.17 之前提供兼容性。 (由 Jelle Zijlstra 在 gh-105499 中贡献。)

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

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

    • splitattr()

    • splithost()

    • splitnport()

    • splitpasswd()

    • splitport()

    • splitquery()

    • splittag()

    • splittype()

    • splituser()

    • splitvalue()

    • to_bytes()

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

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

  • sys._clear_type_cache() 已弃用,请改用 sys._clear_internal_caches()

CPython 字节码的改变

伪指令

  • Add the ANNOTATIONS_PLACEHOLDER pseudo instruction to support partially executed module-level annotations with deferred evaluation of annotations. (Contributed by Jelle Zijlstra in gh-130907.)

  • 增加 BINARY_OP_EXTEND 伪指令,它会执行从内联缓存中访问的一对函数(守卫函数和特化函数)。 (由 Irit Katriel 在 gh-100239 中贡献。)

  • 增加 CALL_KW 的三个特化版本; CALL_KW_PY 用于对 Python 函数的调用,CALL_KW_BOUND_METHOD 用于对绑定方法的调用,而 CALL_KW_NON_PY 用于所有其他调用。 (由 Mark Shannon 在 gh-118093 中贡献。)

  • 增加 JUMP_IF_TRUEJUMP_IF_FALSE 伪指令,即不影响栈的条件跳转。 由序列 COPY 1, TO_BOOL, POP_JUMP_IF_TRUE/FALSE 替换。 (由 Irit Katriel 在 gh-124285 中贡献。)

  • 增加 LOAD_CONST_MORTAL 伪指令。 (由 Mark Shannon 在 gh-128685 中贡献。)

  • Add the LOAD_CONST_IMMORTAL pseudo instruction, which does the same as LOAD_CONST, but is more efficient for immortal objects. (Contributed by Mark Shannon in gh-125837.)

  • 增加 NOT_TAKEN 伪指令,由 sys.monitoring 用来记录分支事件 (如 BRANCH_LEFT)。 (由 Mark Shannon 在 gh-122548 中贡献。)

C API 的变化

Python configuration C API

新增 PyInitConfig C API 用于配置 Python 初始化过程,无需依赖 C 结构体,同时支持未来进行 ABI 兼容性变更。

Complete the PEP 587 PyConfig C API by adding PyInitConfig_AddModule() which can be used to add a built-in extension module; a feature previously referred to as the "inittab".

新增 PyConfig_Get()PyConfig_Set() 函数,用于获取和设置当前运行时配置。

PEP 587 'Python Initialization Configuration' unified all the ways to configure Python's initialization. This PEP also unifies the configuration of Python's preinitialization and initialization in a single API. Moreover, this PEP only provides a single choice to embed Python, instead of having two 'Python' and 'Isolated' choices (PEP 587), to further simplify the API.

The lower level PEP 587 PyConfig API remains available for use cases with an intentionally higher level of coupling to CPython implementation details (such as emulating the full functionality of CPython's CLI, including its configuration mechanisms).

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

参见

PEP 741 and PEP 587

C API 中的新特性

受限 C API 的变化

被移除的 C API

  • 使用可变基类创建 不可变类型 的做法自 Python 3.12 起已被弃用,现在将会引发 TypeError。 (由 Nikita Sobolev 在 gh-119775 中贡献。)

  • 移除在 Python 3.12 中已被弃用的 PyDictObject.ma_version_tag 成员。 请改用 PyDict_AddWatcher() API。 (由 Sam Gross 在 gh-124296 中贡献。)

  • 移除私有函数 _Py_InitializeMain()。该函数是 PEP 587 在 Python 3.8 中引入的 provisional API。 (由 Victor Stinner 在 gh-129033 中贡献。)

  • 移除了未写入文档的 API Py_C_RECURSION_LIMITPyThreadState.c_recursion_remaining。 它们在 3.13 中增加并且未宣布弃用即被移除。 请在 C 代码中使用 Py_EnterRecursiveCall() 来防范无限递归问题。 (由 Petr Viktorin 在 gh-133079 中移除,另请参阅 gh-130396。)

已弃用的 C API

计划在 Python 3.15 中移除

计划在 Python 3.16 中移除

  • 捆绑的 libmpdec 副本。

计划在 Python 3.18 中移除

计划在未来版本中移除

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

Build changes

  • PEP 776: Emscripten is now an officially supported platform at tier 3. As a part of this effort, more than 25 bugs in Emscripten libc were fixed. Emscripten now includes support for ctypes, termios, and fcntl, as well as experimental support for the new default interactive shell. (Contributed by R. Hood Chatham in gh-127146, gh-127683, and gh-136931.)

  • Official Android binary releases are now provided on python.org.

  • 生成 configure 文件现在需要 GNU Autoconf 2.72 版本。(由 Erlend Aasland 在 gh-115765 中贡献。)

  • wasm32-unknown-emscripten 现已成为 PEP 11 标准中的第三级(Tier 3)支持平台。(由 R. Hood Chatham 在 gh-127146gh-127683gh-136931 中贡献。)

  • 现在可以通过 Py_NO_LINK_LIB 关闭基于 #pragmapython3*.lib 的链接。(由 Jean-Christophe Fillion-Robin 在 gh-82909 中贡献。)

  • CPython 现在默认启用了一组推荐的编译器选项以增强安全性。如需禁用这些选项,可使用 --disable-safety configure 选项;若希望启用更大范围的编译器安全选项(但会牺牲性能),则可使用 --enable-slower-safety 选项。

  • WITH_FREELISTS 宏和 --without-freelists configure 选项已被移除。

  • The new configure option --with-tail-call-interp may be used to enable the experimental tail call interpreter. See 一种新型的解释器 for further details.

  • 要禁用新的远程调试支持,请使用 --without-remote-debug configure 选项。 出于安全原因,这可能会有用。

  • iOS 和 macOS 应用程序现在可配置为将 stdoutstderr 输出内容重定向至系统日志。(由 Russell Keith-Magee 在 gh-127592 中贡献。)

  • iOS 测试平台现已支持在测试运行时实时流式传输测试输出,并可用于运行除 CPython 之外的其他项目测试套件。(由 Russell Keith-Magee 在 gh-127592 中贡献。)

build-details.json

现在的 Python 安装包中包含一个新文件:build-details.json。这是一个静态的 JSON 文档,包含 CPython 的构建详情,无需运行代码即可进行内省。这对于 Python 启动器、交叉编译等使用场景很有帮助。

build-details.json 必须安装在与平台无关的标准库目录中。这对应于 'stdlib' sysconfig 安装路径,可通过运行 sysconfig.get_path('stdlib') 找到该路径。

参见

PEP 739 —— build-details.json 1.0——Python 构建详情的静态描述文件

PGP 签名的停用

Python 3.14 及未来的版本将不再提供 PGP (Pretty Good Privacy) 签名。 要验证 CPython 制品,用户必须使用 Sigstore 验证材料。 自 Python 3.11 起的发布版就已采用 Sigstore 进行签名。

发布流程中的这一变更已在 PEP 761 中明确规定。

Free-threaded Python is officially supported

The free-threaded build of Python is now supported and no longer experimental. This is the start of phase II where free-threaded Python is officially supported but still optional.

The free-threading team are confident that the project is on the right path, and appreciate the continued dedication from everyone working to make free-threading ready for broader adoption across the Python community.

With these recommendations and the acceptance of this PEP, the Python developer community should broadly advertise that free-threading is a supported Python build option now and into the future, and that it will not be removed without a proper deprecation schedule.

Any decision to transition to phase III, with free-threading as the default or sole build of Python is still undecided, and dependent on many factors both within CPython itself and the community. This decision is for the future.

实验性即时编译器(JIT)的二进制发布版本

官方 macOS 和 Windows 发布版二进制文件现已包含 实验性 即时编译(JIT)器。虽然不建议在生产环境中使用,但可通过设置环境变量 PYTHON_JIT=1 进行测试。下游源码构建和再分发方可使用配置选项 --enable-experimental-jit=yes-off 实现类似行为。

该JIT编译器尚处于早期开发阶段,性能表现存在波动:启用后根据工作负载不同,可能产生10%的性能下降至20%的性能提升。为便于测试评估,sys._jit 命名空间提供了一组内省函数:sys._jit.is_available() 用于检测当前可执行文件是否支持JIT编译,而 sys._jit.is_available() 则可判断当前进程是否已启用JIT编译功能。

当前最显著的功能缺失是原生调试器(如 gdb)和性能分析工具(如 perf)无法展开JIT调用栈(而Python原生调试器如 pdb 和性能分析器如 profile 仍可无需修改直接使用)。此外,自由线程构建版本暂不支持JIT编译功能。

如遇任何错误或严重性能退化问题,请务必提交报告!

参见

PEP 744

移植到 Python 3.14

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

Python API 的变化

  • On Unix platforms other than macOS, forkserver is now the default start method for multiprocessing and ProcessPoolExecutor, instead of fork.

    请参阅 (1)(2) 了解详情。

    如果你在 multiprocessingconcurrent.futures 中遇到 NameError 或 pickle 错误,请参阅 forkserver 的限制

    This change does not affect Windows or macOS, where 'spawn' remains the default start method.

  • functools.partial 现在是一个方法描述符。若需保持原有行为,请将其包装在 staticmethod() 中。(由 Serhiy Storchaka 和 Dominykas Grigonis 在 gh-121027 中贡献。)

  • 垃圾回收器现在是增量式的,这意味着 gc.collect() 的行为有轻微改变:

    • gc.collect(1):执行一次增量式垃圾回收,而非专门回收第1代对象。

    • gc.collect() 的其他调用保持不变。

  • locale.nl_langinfo() 函数现在会在某些情况下临时设置 LC_CTYPE 区域设置。这种临时修改会影响其他线程。(由 Serhiy Storchaka 在 gh-69998 中贡献。)

  • types.UnionType 现在是 typing.Union 的别名,这会导致部分行为发生变化。更多细节请参见 上文。(由 Jelle Zijlstra 在 gh-105499 中贡献。)

  • The runtime behavior of annotations has changed in various ways; see above for details. While most code that interacts with annotations should continue to work, some undocumented details may behave differently.

  • As part of making the mimetypes CLI public, it now exits with 1 on failure instead of 0 and 2 on incorrect command-line parameters instead of 1. Error messages are now printed to stderr.

  • The \B pattern in regular expression now matches the empty string when given as the entire pattern, which may cause behavioural changes.

  • 在 FreeBSD 上,sys.platform 不再包含主版本号。

标注中的变化 (PEP 649PEP 749)

This section contains guidance on changes that may be needed to annotations or Python code that interacts with or introspects annotations, due to the changes related to deferred evaluation of annotations.

In the majority of cases, working code from older versions of Python will not require any changes.

注解代码的影响

如果在代码中定义注解(例如用于静态类型检查器),那么这一变更可能不会产生影响:你可以继续保持与之前Python版本相同的注解书写方式。

你很可能可以移除注解中的引号字符串(这些通常用于前向引用)。同样地,如果使用 from __future__ import annotations 来避免在注解中书写字符串,当你仅支持 Python 3.14 及更新版本时,很可能可以移除该导入。不过,如果依赖读取注解的第三方库,这些库可能需要相应修改以支持无引号注解,才能正常工作。

访问 __annotations__ 的影响

If your code reads the __annotations__ attribute on objects, you may want to make changes in order to support code that relies on deferred evaluation of annotations. For example, you may want to use annotationlib.get_annotations() with the FORWARDREF format, as the dataclasses module now does.

外部包 typing_extensions 提供了 annotationlib 模块部分功能的向后兼容实现,包括 Format 枚举和 get_annotations() 函数。这些可用于编写跨版本代码,以利用 Python 3.14 中的新行为。

from __future__ import annotations

In Python 3.7, PEP 563 introduced the from __future__ import annotations future statement, which turns all annotations into strings.

However, this statement is now deprecated and it is expected to be removed in a future version of Python. This removal will not happen until after Python 3.13 reaches its end of life in 2029, being the last version of Python without support for deferred evaluation of annotations.

在 Python 3.14 中,使用 from __future__ import annotations 的代码的行为将没有变化。

C API 的变化

  • Py_Finalize() 现在会删除所有已驻留字符串。 这一变更将不向下兼容任何在调用 Py_Finalize() 后仍拥有驻留字符串并在后续调用 Py_Initialize() 时重复使用的 C 扩展模块。 此行为引发的任何问题通常会导致在后续 Py_Initialize() 调用执行期间因访问未初始化内存而引发崩溃。 要修复此问题,应使用地址静化器来标识任何来自驻留字符串的释放后使用并在模块关闭期间释放它。 (由 Eddie Elizondo 在 gh-113601 中贡献。)

  • Unicode异常对象 C API现会在异常参数不是 UnicodeError 对象时抛出 TypeError 异常。(由Bénédikt Tran在 gh-127691 中贡献)