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 版本进行升级的指导。
解释器的改进:
标准库中的重大改进:
默认交互式 shell 中的语法高亮,以及多个标准库 CLI 中的彩色输出
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 749 和 gh-119180 中贡献;PEP 649 由 Larry Hastings 编写。)
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 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 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 中描述的协议,它详细讲解了用于安全附加到运行进程的底层机制。
该调试接口在设计时已充分考虑安全性,并包含多种访问控制机制:
-X disable-remote-debug
命令行选项。--without-remote-debug
配置标志,用于在构建时完全禁用此功能。
(由 Pablo Galindo Salgado,Matt Wozniski 和 Ivona Stojanovic 在 gh-131591 中贡献)
参见
一种新型的解释器¶
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 ofpass
,break
, orcontinue
is passed beforeif
, then the error message highlights where theexpression
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 ...
尝试向
dict
或set
添加不可哈希类型的实例时,错误提示信息已改进。(由 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压缩归档文件的读写支持也已添加到 tarfile
、zipfile
和 shutil
模块中。
下面是一个使用新模块压缩数据的示例:
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与 lzma
和 bz2
模块的API类似。
(由 Emma Harper Smith、Adam Turner、Gregory P. Smith、Tomas Roun、Victor Stinner 和 Rogdham 在 gh-132983 中贡献。)
参见
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 ofawait
, and asynchronous comprehensions outside asynchronous functions. For example,python -O -c 'assert (__debug__ := 1)'
orpython -O -c 'assert await 1'
now produceSyntaxError
s. (Contributed by Irit Katriel and Jelle Zijlstra in gh-122245 & gh-121637.)当纯C类型派生子类时,若子类未显式重写相关方法,新建类型的C槽位将不再被替换为封装版本。(由 Tomasz Pytel 在 gh-132284 中贡献。)
内置¶
bytes.fromhex()
和bytearray.fromhex()
方法现在支持 ASCII 格式的bytes
及 字节型对象 作为输入参数。(由 Daniel Pope 在 gh-129349 中贡献。)新增类方法
float.from_number()
和complex.from_number()
,用于将数值分别转换为float
或complex
类型。若参数不是一个实数则会引发TypeError
。(由 Serhiy Storchaka 在 gh-84978 中贡献。)在新式字符串格式化(通过
format()
或 f-字符串 实现)的浮点数表示类型中,现支持使用下划线和逗号作为小数部分的千位分隔符。(由 Sergey B Kirpichev 在 gh-87790 中贡献。)int()
函数不再委托给__trunc__()
。 希望支持转换为int()
的类必须实现__int__()
或__index__()
。 (由 Mark Dickinson 在 gh-119743 中贡献。)map()
函数现在新增了一个可选的仅限关键字参数 strict (与zip()
类似),用于校验所有可迭代对象长度是否一致。(由 Wannes Boeykens 在 gh-119793 中贡献。)memoryview
类型现已支持下标,使其成为 generic type。 (由 Brian Schubert 在 gh-126012 中贡献。)在布尔上下文中使用
NotImplemented
现在会引发TypeError
异常。该用法自 Python 3.9 起已引发DeprecationWarning
弃用警告。(由 Jelle Zijlstra 在 gh-118767 中贡献。)三参数
pow()
现在会在必要时尝试调用__rpow__()
方法。此前该方法仅在双参数pow()
和二元幂运算符中被调用。(由 Serhiy Storchaka 在 gh-130104 中贡献。)super
对象现在支持复制
和序列化
操作。(由 Serhiy Storchaka 在 gh-125767 中贡献。)
命令行与环境¶
导入时间分析标志现可通过新增的
-X importtime=2
选项追踪已加载('缓存')模块。当导入此类模块时,self
和cumulative
时间值将被替换为字符串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: 允许不带圆括号的 except
和 except*
表达式¶
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!')
PEP 765: finally
代码块中的控制流¶
编译器在检测到 return
、break
或 continue
语句跳出 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 thePYTHONSTARTUP
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 withco
. Similarly, typingfrom concurrent import i
will suggest submodules ofconcurrent
starting withi
. 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
(includingcompression.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¶
名为
create_task()
的函数及方法现在接受任意关键字参数列表,所有关键字参数都将传递给Task
构造器或自定义任务工厂(详见set_task_factory()
)。name
和context
关键字参数不再具有特殊处理逻辑——名称现在应通过工厂的name
关键字参数设置,而context
可设为None
。This affects the following function and methods:
asyncio.create_task()
,asyncio.loop.create_task()
,asyncio.TaskGroup.create_task()
.(Contributed by Thomas Grainger in gh-128307.)
There are two new utility functions for introspecting and printing a program's call graph:
capture_call_graph()
andprint_call_graph()
. See Asyncio introspection capabilities for more details. (Contributed by Yury Selivanov, Pablo Galindo Salgado, and Łukasz Langa in gh-91048.)
calendar(日历)¶
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()
andkill_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 towrite()
keys containing delimiters or beginning with the section header pattern will raise anInvalidWriteError
. (Contributed by Jacob Lincoln in gh-129270.)
contextvars¶
已为
Token
对象提供 context manager 协议支持。 (由 Andrew Svetlov 在 gh-129889 中贡献。)
ctypes¶
The layout of bit fields in
Structure
andUnion
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平台上,
CopyComPointer()
函数现已公开。(由 Jun Komoda 在 gh-127275 中贡献。)Add
memoryview_at()
, a function to create amemoryview
object that refers to the supplied pointer and length. This works likectypes.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
, andc_longdouble_complex
, are now available if both the compiler and thelibffi
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 correspondingctypes
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¶
增加
assume_default_colors()
函数,是将use_default_colors()
函数改进为允许修改颜色对0
。 (由 Serhiy Storchaka 在 gh-133139 中贡献。)
datetime¶
为
datetime.date
和 anddatetime.time
类增加strptime()
方法。 (由 Wannes Boeykens 在 gh-41431 中贡献。)
decimal¶
增加
Decimal.from_number()
作为Decimal
的替代性构造器。 (由 Serhiy Storchaka 在 gh-121798 中贡献。)对外公开
IEEEContext()
以支持创建对应与 IEEE 754 (2008) 十进制交换格式的上下文。 (由 Sergey B Kirpichev 在 gh-53032 中贡献。)
difflib¶
dis¶
新增对
指令
完整源码位置信息(而非仅行号)的渲染支持,该特性通过 show_positions 关键字参数添加到以下接口:该特性同时通过
dis --show-positions
命令行选项提供。(由 Bénédikt Tran 在 gh-123165 中贡献。)新增
dis --specialized
命令行选项,用于显示特化字节码。(由 Bénédikt Tran 在 gh-127413 中贡献。)
errno¶
faulthandler¶
Add support for printing the C stack trace on systems that support it via the new
dump_c_stack()
function or via the c_stack argument infaulthandler.enable()
. (Contributed by Peter Bierma in gh-127604.)
fnmatch¶
Add
filterfalse()
, a function to reject names matching a given pattern. (Contributed by Bénédikt Tran in gh-74598.)
fractions¶
A
Fraction
object may now be constructed from any object with theas_integer_ratio()
method. (Contributed by Serhiy Storchaka in gh-82017.)Add
Fraction.from_number()
as an alternative constructor forFraction
. (Contributed by Serhiy Storchaka in gh-121797.)
functools¶
Add the
Placeholder
sentinel. This may be used with thepartial()
orpartialmethod()
functions to reserve a place for positional arguments in the returned partial object. (Contributed by Dominykas Grigonis in gh-119127.)Allow the initial parameter of
reduce()
to be passed as a keyword argument. (Contributed by Sayandip Dutta in gh-125916.)
getopt¶
getpass¶
graphlib¶
允许在排序尚未开始的情况下多次调用
TopologicalSorter.prepare()
。 (由 Daniel Pope 在 gh-130914 中贡献。)
heapq¶
通过下列新增函数,
heapq
模块改进了对最大堆的支持:
hmac¶
http¶
由
http.server
模块生成的目录列表和错误页面允许浏览器应用其默认暗模式。(由 Yorik Hansen 在 gh-123430 中贡献。)http.server
模块现在支持使用http.server.HTTPSServer
类通过 HTTPS 提供服务。此功能通过命令行界面 (python -m http.server
) 通过以下选项公开:--tls-cert <path>
: TLS 证书文件的路径。--tls-key <path>
: 可选的私钥文件路径。--tls-password-file <path>
: 可选的私钥密码文件路径。
(由 Semyon Moroz 在 gh-85162 中贡献。)
imaplib¶
Add
IMAP4.idle()
, implementing the IMAP4IDLE
command as defined in RFC 2177. (Contributed by Forest in gh-55454.)
inspect¶
signature()
takes a new argument annotation_format to control theannotationlib.Format
used for representing annotations. (Contributed by Jelle Zijlstra in gh-101552.)Signature.format()
takes a new argument unquote_annotations. If true, string annotations are displayed without surrounding quotes. (Contributed by Jelle Zijlstra in gh-101552.)Add function
ispackage()
to determine whether an object is a package or not. (Contributed by Zhikang Yan in gh-125634.)
io¶
使用
read
从非阻塞流读取文本时,如果操作无法立即返回字节,现在可能会引发BlockingIOError
。(由 Giovanni Siragusa 在 gh-109523 中贡献。)Add the
Reader
andWriter
protocols as simpler alternatives to the pseudo-protocolstyping.IO
,typing.TextIO
, andtyping.BinaryIO
. (Contributed by Sebastian Rittau in gh-127648.)
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¶
logging.handlers¶
QueueListener
objects now support the context manager protocol. (Contributed by Charles Machalow in gh-132106.)QueueListener.start
现在如果监听器已启动,会引发RuntimeError
。(由 Charles Machalow 在 gh-132106 中贡献。)
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 viaset_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.)针对 list 和 dict 类型的 多进程代理对象 增加了此前被忽略的缺失方法:
clear()
和copy()
用于list
的代理fromkeys()
、reversed(d)
、d | {}
、{} | d
、d |= {'b': 2}
用于dict
的代理
(由 Roy Hyunjin Han 在 gh-103134 中贡献。)
Add support for shared
set
objects viaSyncManager.set()
. Theset()
inManager()
method is now available. (Contributed by Mingyu Park in gh-129949.)Add the
interrupt()
tomultiprocessing.Process
objects, which terminates the child process by sendingSIGINT
. This enablesfinally
clauses to print a stack trace for the terminated process. (Contributed by Artem Pulkin in gh-131913.)
operator¶
Add
is_none()
andis_not_none()
as a pair of functions, such thatoperator.is_none(obj)
is equivalent toobj is None
andoperator.is_not_none(obj)
is equivalent toobj is not None
. (Contributed by Raymond Hettinger and Nico Mexis in gh-115808.)
os¶
Add the
reload_environ()
function to updateos.environ
andos.environb
with changes to the environment made byos.putenv()
, byos.unsetenv()
, or made outside Python in the same process. (Contributed by Victor Stinner in gh-120057.)Add the
SCHED_DEADLINE
andSCHED_NORMAL
constants to theos
module. (Contributed by James Roy in gh-127688.)Add the
readinto()
function to read into a buffer object from a file descriptor. (Contributed by Cody Maloney in gh-129205.)
os.path¶
The strict parameter to
realpath()
accepts a new value,ALLOW_MISSING
. If used, errors other thanFileNotFoundError
will be re-raised; the resulting path can be missing but it will be free of symlinks. (Contributed by Petr Viktorin for CVE 2025-4517.)
pathlib¶
为
pathlib.Path
新增递归复制/移动文件和目录的方法:copy()
将一个文件或目录树复制到目标位置。copy_into()
会将内容复制 到 目标目录中。move()
将一个文件或目录树移动到目标位置。move_into()
会将内容移动 到 目标目录中。
(由 Barney Gale 在 gh-73991 中贡献。)
Add the
info
attribute, which stores an object implementing the newpathlib.types.PathInfo
protocol. The object supports querying the file type and internally cachingstat()
results. Path objects generated byiterdir()
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()
andset_trace()
) now reuse the most recentPdb
instance that callsset_trace()
, instead of creating a new one each time. As a result, all the instance specific data likedisplay
andcommands
are preserved across hardcoded breakpoints. (Contributed by Tian Gao in gh-121450.)为
pdb.Pdb
新增一个 mode 参数。当pdb
处于inline
模式时,禁用restart
命令。(由 Tian Gao 在 gh-123757 中贡献。)当用户尝试在
inline
模式下退出pdb
时,会显示一个确认提示。输入y
、Y
、按<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 addedcolorize
argument ofpdb.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¶
Add
invalidate_caches()
, a function to invalidate cached results in theplatform
module. (Contributed by Bénédikt Tran in gh-122549.)
pydoc¶
re¶
在
正则表达式
中,现支持将\z
作为\Z
的同义符使用。与行为存在微妙差异的\Z
不同,\z
在其他多种正则表达式引擎中具有明确无歧义的解析方式。(由 Serhiy Storchaka 在 gh-133306 中贡献。)\B
inregular 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
地址中 cid 和 bdaddr_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¶
struct¶
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¶
Add two new monitoring events,
BRANCH_LEFT
andBRANCH_RIGHT
. These replace and deprecate theBRANCH
event. (Contributed by Mark Shannon in gh-122548.)
sysconfig¶
Add
ABIFLAGS
key toget_config_vars()
on Windows. (Contributed by Xuehai Pan in gh-131799.)
tarfile¶
data_filter()
现在会对符号链接目标进行规范化处理,以避免路径遍历攻击。(由 Petr Viktorin 在 gh-127987 和 CVE 2025-4138 中贡献。)extractall()
现在在目录被移除或被其他类型的文件替换时,会跳过对目录属性的修复。(由 Petr Viktorin 在 gh-127987 和 CVE 2024-12718 中贡献。)extract()
和extractall()
现在在以下两种情况会(重新)应用提取过滤器:一是用另一个归档成员的副本替换链接(硬链接或符号链接)时,二是修复目录属性时。前者会引发一个新异常LinkFallbackError
。(由 Petr Viktorin 针对 CVE 2025-4330 和 CVE 2024-12718 贡献。)extract()
和extractall()
在errorlevel()
为 0 时,不再提取被拒绝的成员。(由 Matt Prodani 和 Petr Viktorin 在 gh-112887 以及 CVE 2025-4435 中贡献。)
threading¶
threading.Thread.start()
现在会将操作系统线程名称设置为threading.Thread.name
。(由 Victor Stinner 在 gh-59705 中贡献。)
tkinter¶
turtle(海龟绘图)¶
Add context managers for
turtle.fill()
,turtle.poly()
, andturtle.no_animation()
. (Contributed by Marie Roald and Yngve Mardal Moe in gh-126350.)
types(类型)¶
types.UnionType
现在是typing.Union
的别名。更多详情请参见 下方。(由 Jelle Zijlstra 在 gh-105499 中贡献。)
typing¶
The
types.UnionType
andtyping.Union
types are now aliases for each other, meaning that both old-style unions (created withUnion[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 beTrue
), but now it will return two different objects. Use==
to compare unions for equality, notis
. 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 subscriptingtyping.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 oftypes.UnionType
is itself much smaller than the object returned byUnion[]
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 likeget_origin()
andtyping.get_args()
instead of relying on private implementation details.现在可以在
isinstance()
检查中使用typing.Union
本身。例如,isinstance(int | str, typing.Union)
将返回True
;而此前这会引发TypeError
。The
__args__
attribute oftyping.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¶
unittest
模块的输出现在默认启用彩色显示,可通过 环境变量 进行控制。(由 Hugo van Kemenade 在 gh-127221 中贡献。)unittest 发现机制重新支持将 namespace package 作为起始目录,该功能曾在 Python 3.11 中被移除。 (由 Jacob Walls 在 gh-80958 中贡献。)
在
TestCase
类中新增了多个方法,这些方法可提供更专门化的测试。assertHasAttr()
andassertNotHasAttr()
check whether the object has a particular attribute.assertIsSubclass()
和assertNotIsSubclass()
用于检查对象是否是某个特定类的子类,或者是否是某个类元组中任一类的子类。assertStartsWith()
、assertNotStartsWith()
、assertEndsWith()
和assertNotEndsWith()
用于检查 Unicode 字符串或字节串是否以特定字符串开头或结尾。
(由 Serhiy Storchaka 在 gh-71339 中贡献。)
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¶
增加
ZipInfo._for_archive
方法,用于为ZipInfo
对象解析适当的默认值并由ZipFile.writestr
使用。 (由 Bénédikt Tran 在 gh-123424 中贡献。)ZipFile.writestr()
现在会遵从SOURCE_DATE_EPOCH
环境变量设置以便更好地支持可复现的构建。 (由 Jiahao Li 在 gh-91279 中贡献。)
性能优化¶
几个标准库模块的导入时间已得到改进,包括
annotationlib
、ast
、asyncio
、base64
、cmd
、csv
、gettext
、importlib.util
、locale
、mimetypes
、optparse
、pickle
、pprint
、pstats
、shlex
、socket
、string
、subprocess
、threading
、tomllib
、types
和zipfile
。(由 Adam Turner、Bénédikt Tran、Chris Markiewicz、Eli Schwartz、Hugo van Kemenade、Jelle Zijlstra 等人在 gh-118761 中贡献。)
The interpreter now avoids some reference count modifications internally when it's safe to do so. This can lead to different values being returned from
sys.getrefcount()
andPy_REFCNT()
compared to previous versions of Python. See below for details.
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¶
pathlib¶
Path.read_bytes
现在使用无缓冲模式打开文件,完整读取的速度提高了 9% 到 17%。(由 Cody Maloney 在 gh-120754 中贡献。)
pdb¶
pdb
现在支持两种后端,基于sys.settrace()
或sys.monitoring
。使用 pdb CLI 或breakpoint()
将始终使用sys.monitoring
后端。显式实例化pdb.Pdb
及其派生类将默认使用sys.settrace()
后端,这是可配置的。(由 Tian Gao 在 gh-124533 中贡献。)
uuid¶
zlib¶
移除¶
argparse¶
移除
BooleanOptionalAction
的 type、 choices 和 metavar 形参。 它们自 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_Num
、visit_Str
、visit_Bytes
、visit_NameConstant
和visit_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¶
移除已弃用的
importlib.abc
类:ResourceReader
(使用TraversableResources
)Traversable
(使用Traversable
)TraversableResources
(使用TraversableResources
)
(由 Jason R. Coombs 和 Hugo van Kemenade 在 gh-93963 中贡献。)
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¶
从
sqlite3
模块中移除version
和version_info
;请使用sqlite_version
和sqlite_version_info
来获取运行时 SQLite 库的实际版本号。(由 Hugo van Kemenade 在 gh-118924 中贡献。)现在,使用带具名占位符的形参序列会引发
ProgrammingError
异常,该用法自 Python 3.12 起已被弃用。(由 Erlend E. Aasland 在 gh-118928 和 gh-101693 中贡献。)
urllib¶
从
urllib.parse
模块中移除Quoter
类,该类自 Python 3.11 起已被弃用。(由 Nikita Sobolev 在 gh-118827 中贡献。)从
urllib.request
模块中移除URLopener
和FancyURLopener
类,这两个类自 Python 3.3 起已被弃用。myopener.open()
可以替换为urlopen()
。myopener.retrieve()
可以替换为urlretrieve()
。对 opener 类的自定义操作可以通过向build_opener()
传递定制化的处理程序来实现替换。(由 Barney Gale 在 gh-84850 中贡献。)
弃用¶
新的弃用¶
传入一个复数作为
complex()
构造器中的 real 或 imag 参数的做法现已被弃用;复数应当仅作为单个位置参数被传入。 (由 Serhiy Storchaka 在 gh-109218 中贡献。)-
将未写入文档的关键字参数 prefix_chars 传给
add_argument_group()
方法的做法现已被弃用。 (由 Savannah Ostrowski 在 gh-125563 中贡献。)已弃用
argparse.FileType
类型转换器。 任何涉及资源管理的操作都应在参数解析完成之后在下游进行处理。 (由 Serhiy Storchaka 在 gh-58032 中贡献。)
-
现在
asyncio.iscoroutinefunction()
已被弃用并将在 Python 3.16 中移除;请改用inspect.iscoroutinefunction()
。 (由 Jiahao Li 和 Kumar Aditya 在 gh-122875 中贡献。)asyncio
策略系统已被弃用并将在 Python 3.16 中移除。 具体而言,是弃用了下列类和函数:用户应当使用
asyncio.run()
或asyncio.Runner
并附带 loop_factory 参数以使用想要的事件循环实现。例如,在 Windows 上使用
asyncio.SelectorEventLoop
:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(由 Kumar Aditya 在 gh-127949 中贡献。)
codecs
:codecs.open()
函数现已被弃用,并将在未来的 Python 版本中移除。 请改用open()
。 (由 Inada Naoki 在 gh-133036 中贡献。)-
在非 Windows 平台上,设置
Structure._pack_
以使用 MSVC 兼容的默认内存布局的做法现已被弃用而应改为设置Structure._layout_
to'ms'
,并将在 Python 3.19 中移除。 (由 Petr Viktorin 在 gh-131747 中贡献。)在字符串上调用
ctypes.POINTER()
的做法现已被弃用。 对于自引用的结构体请使用 不完整类型。 此外,内部的ctypes._pointer_type_cache
也已被弃用。 请参阅ctypes.POINTER()
了解更新的实现细节。 (由 Sergey Myrianov 在 gh-100926 中贡献。)
functools
: 调用functools.reduce()
的 Python 实现时以关键字参数形式传入 function 或 sequence 的做法现已被弃用;这两个形参将在 Python 3.16 中改为仅限位置形参。 (由 Kirill Podoprigora 在 gh-121676 中贡献。)logging
: 对使用 strm 参数的自定义日志处理器的支持现已被弃用并计划在 Python 3.16 中移除。 请改为定义伤脑筋 stream 参数的处理器。 (由 Mariusz Felisiak 在 gh-115032 中贡献。)mimetypes
: 对于mimetypes.MimeTypes.add_type()
有效的扩展名应为空或者必须以 '.' 打头。 不带点号的扩展名已被弃用并将在 Python 3.16 中引发ValueError
。 (由 Hugo van Kemenade 在 gh-75223 中贡献。)nturl2path
: 该模块现已弃用,请改用urllib.request.url2pathname()
和pathname2url()
。(由 Barney Gale 在 gh-125866 中贡献。)os
: 现在os.popen()
和os.spawn*
函数都被设为 soft deprecated。 它们不应再用于编写新的代码。 建议改用subprocess
模块。 (由 Victor Stinner 在 gh-120743 中贡献。)pathlib
: 现在pathlib.PurePath.as_uri()
已被弃用将计划在 Python 3.19 中移除。 请改用pathlib.Path.as_uri()
。 (由 Barney Gale 在 gh-123599 中贡献。)pdb
: 未写入文档的pdb.Pdb.curframe_locals
属性现在成为已弃用的只读特性属性,它将在未来的 Python 版本中被移除。 通过 PEP 667 在 Python 3.13 中添加的低开销动态帧局部变量访问机制使得之前存储在该属性中的帧局部变量缓存引用已不再需要。 派生的调试器在 Python 3.13 及更高版本中应当直接访问pdb.Pdb.curframe.f_locals
。 (由 Tian Gao 在 gh-124369 和 gh-125951 中贡献。)symtable
: 由于缺少兴趣symtable.Class.get_methods()
已被弃用,计划在 Python 3.16 中移除。 (由 Bénédikt Tran 在 gh-119698 中贡献。)tkinter
:tkinter.Variable
的方法trace_variable()
、trace_vdelete()
和trace_vinfo()
现已被弃用。请改用trace_add()
、trace_remove()
和trace_info()
。(由 Serhiy Storchaka 在 gh-120220 中贡献。)urllib.parse
: 在parse_qsl()
和parse_qs()
中接受除空字符串、字节型对象以及None
之外的假值 (如0
和[]
) 的做法现已被弃用。 (由 Serhiy Storchaka 在 gh-116897 中贡献。)
计划在 Python 3.15 中移除¶
导入系统:
当设置
__spec__.cached
失败时在模块上设置__cached__
的做法已被弃用。 在 Python 3.15 中,__cached__
将不会再被导入系统或标准库纳入考虑。 (gh-97879)当设备
__spec__.parent
失败时在模块上设置__package__
的做法已被弃用。 在 Python 3.15 中,__package__
将不会再被导入系统或标准库纳入考虑。 (gh-97879)
-
未写入文档的
ctypes.SetPointerType()
函数自 Python 3.13 起已被弃用。
-
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 起已被弃用。
-
load_module()
方法:改用exec_module()
。
-
getdefaultlocale()
函数自 Python 3.11 起已被弃用。 最初计划在 Python 3.13 中移除它 (gh-90817),但已被推迟至 Python 3.15。 请改用getlocale()
,setlocale()
和getencoding()
。 (由 Hugo van Kemenade 在 gh-111187 中贡献。)
-
.PurePath.is_reserved()
has been deprecated since Python 3.13. Useos.path.isreserved()
to detect reserved paths on Windows.
-
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.is_python_build()
的 check_home 参数自 Python 3.12 起已被弃用。
-
在 Python 3.15 中
RLock()
将不再接受参数。 传入参数的做法自 Python 3.14 起已被弃用,因为 Python 版本不接受任何参数,而 C 版本允许任意数量的位置或关键字参数,但会忽略所有参数。
-
types.CodeType
: 访问co_lnotab
的做法自 3.10 起已根据 PEP 626 被弃用并曾计划在 3.12 中移除,但在 3.12 中实际仅设置了DeprecationWarning
。 可能会在 3.15 中移除。 (由 Nikita Sobolev 在 gh-101866 中贡献。)
-
未写入文档的用于创建
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): pass
或TD = TypedDict("TD", {})
来创建一个零字段的 TypedDict。typing.no_type_check_decorator()
装饰器自 Python 3.13 起已被弃用。 存在于typing
模块八年之后,它仍未被任何主要类型检查器所支持。
sre_compile
,sre_constants
和sre_parse
模块。wave
:The
getmark()
,setmark()
andgetmarkers()
methods of theWave_read
andWave_write
classes have been deprecated since Python 3.13.
-
zipimport.zipimporter.load_module()
has been deprecated since Python 3.10. Useexec_module()
instead. (gh-125746.)
计划在 Python 3.16 中移除¶
导入系统:
当设置
__spec__.loader
失败时在模块上设置__loader__
的做法已被弃用。 在 Python 3.16 中,__loader__
将不会再被设置或是被导入系统或标准库纳入考虑。
-
'u'
格式代码 (wchar_t
) 自 Python 3.3 起已在文档中弃用并自 Python 3.13 起在运行时弃用。 对于 Unicode 字符请改用'w'
格式代码 (Py_UCS4
)。
-
asyncio.iscoroutinefunction()
已被弃用并将在 Python 3.16 中移除,请改用inspect.iscoroutinefunction()
。 (由李佳昊和 Kumar Aditya 在 gh-122875 中贡献。)asyncio
策略系统已被弃用并将在 Python 3.16 中移除。 具体而言,是弃用了下列类和函数:用户应当使用
asyncio.run()
或asyncio.Runner
并附带 loop_factory 以使用想要的事件循环实现。例如,在 Windows 上使用
asyncio.SelectorEventLoop
:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(由 Kumar Aditya 在 gh-127949 中贡献。)
-
对布尔类型
~True
或~False
执行按位取反的操作自 Python 3.12 起已被弃用,因为它会产生奇怪和不直观的结果 (-2
and-1
)。 请改用not x
来对布尔值执行逻辑否操作。 对于需要对下层整数执行按位取反操作的少数场合,请显式地将其转换为int
(~int(x)
)。
-
调用
functools.reduce()
的 Python 实现并传入 function 或 sequence 作为关键字参数的做法自 Python 3.14 起已被弃用。
-
使用 strm 参数对自定义日志记录处理器提供支持的做法已被弃用并计划在 Python 3.16 中移除。 改为使用 stream 参数定义处理器。 (由 Mariusz Felisiak 在 gh-115032 中贡献。)
-
有效扩展以 ". " 开头或在
mimetypes.MimeTypes.add_type()
为空。 未加点的扩展已弃用,在 Python 3.16 中将引发ValueError
。 (由 Hugo van Kemenade 在 gh-75223 中贡献。)
-
ExecError
异常自 Python 3.14 起已被弃用。 它自 Python 3.4 起就未被shutil
中的任何函数所使用,现在是RuntimeError
的一个别名。
-
Class.get_methods
方法自 Python 3.14 起被弃用。
sys
:_enablelegacywindowsfsencoding()
函数自 Python 3.13 起被弃用。 请改用PYTHONLEGACYWINDOWSFSENCODING
环境变量。
-
自Python 3.14 起,
sysconfig.expand_makefile_vars()
函数已被弃用。请使用sysconfig.get_paths()
的vars
参数代替。
-
未写入文档也未被使用的
TarFile.tarfile
属性自 Python 3.13 起被弃用。
计划在 Python 3.17 中移除¶
-
collections.abc.ByteString
计划在 Python 3.17 中移除。使用
isinstance(obj, collections.abc.Buffer)
来测试obj
是否在运行时实现了 缓冲区协议。 要用于类型标注,则使用Buffer
或是显式指明你的代码所支持类型的并集 (例如bytes | bytearray | memoryview
)。ByteString
原本是想作为bytes
和bytearray
的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是ByteString
的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如memoryview
同样不能被当作是ByteString
的子类型(无论是在运行时还是对于静态类型检查器)。
-
在 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
原本是想作为bytes
和bytearray
的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是ByteString
的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如memoryview
同样不能被当作是ByteString
的子类型(无论是在运行时还是对于静态类型检查器)。
计划在 Python 3.19 中移除¶
-
In hash function constructors such as
new()
or the direct hash-named constructors such asmd5()
andsha256()
, their optional initial data parameter could also be passed a keyword argument nameddata=
orstring=
in varioushashlib
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¶
The
__version__
attribute has been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_info
instead.ctypes.macholib
logging
(__date__
also deprecated)
(Contributed by Hugo van Kemenade in gh-76007.)
计划在未来版本中移除¶
以下API将会被移除,尽管具体时间还未确定。
-
嵌套参数组和嵌套互斥组已被弃用 。
将未写入文档的关键字参数 prefix_chars 传递给
add_argument_group()
的做法现在已被弃用。argparse.FileType
类型转换器已弃用 。
-
生成器:
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
,is
和or
中的一个将会引发语法警告。 在未来的版本中它将改为语法错误。 (gh-87999)对
__index__()
和__int__()
方法返回非 int 类型的支持:将要求这些方法必须返回int
的子类的实例。对
__complex__()
方法返回complex
的子类的支持:将要求这些方法必须返回complex
的实例。将
int()
委托给__trunc__()
方法。传入一个复数作为
complex()
构造器中的 real 或 imag 参数的做法现在已被弃用;它应当仅作为单个位置参数被传入。 (由 Serhiy Storchaka 在 gh-109218 中贡献。).)
calendar
:calendar.January
和calendar.February
常量已被弃用并由calendar.JANUARY
和calendar.FEBRUARY
替代。 (由 Prince Roshan 在 gh-103636 中贡献。)codecs
:codecs.open()
请改用open()
。 (gh-133038)-
utcnow()
: 使用datetime.datetime.now(tz=datetime.UTC)
。utcfromtimestamp()
: 使用datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)
。
gettext
: 复数值必须是一个整数。-
cache_from_source()
debug_override 形参已被弃用:改用 optimization 形参。
-
EntryPoints
元组接口。返回值中隐式的
None
。
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
的方法:threading.Condition.notifyAll()
: 使用notify_all()
。threading.Event.isSet()
: 使用is_set()
。threading.Thread.isDaemon()
,threading.Thread.setDaemon()
: 使用threading.Thread.daemon
属性。threading.Thread.getName()
,threading.Thread.setName()
: 使用threading.Thread.name
属性。threading.currentThread()
: 使用threading.current_thread()
。threading.activeCount()
: 使用threading.active_count()
。
内部类
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 字节码的改变¶
将操作码
BINARY_SUBSCR
替换为附带操作数NB_SUBSCR
的BINARY_OP
操作码。 (由 Irit Katriel 在 gh-100239 中贡献。)Add the
BUILD_INTERPOLATION
andBUILD_TEMPLATE
opcodes to construct newInterpolation
andTemplate
instances, respectively. (Contributed by Lysandros Nikolaou and others in gh-132661; see also PEP 750: Template strings).移除了
BUILD_CONST_KEY_MAP
操作码。 改用BUILD_MAP
。 (由 Mark Shannon 在 gh-122160 中贡献。)将
LOAD_ASSERTION_ERROR
操作码替换为LOAD_COMMON_CONSTANT
并添加对载入NotImplementedError
的支持。增加
LOAD_FAST_BORROW
和LOAD_FAST_BORROW_LOAD_FAST_BORROW
操作码用于在解释器能证明帧内引用的生命期长于载入到栈的引用时减少引用计数开销。 (由 Matt Page 在 gh-130704 中贡献。).)增加
LOAD_SMALL_INT
操作码,它会将一个等于oparg
的小整数推入栈。RETURN_CONST
操作码已被移除因为它已不再被使用。 (由 Mark Shannon 在 gh-125837 中贡献。).)新增
LOAD_SPECIAL
指令。 为with
和async with
语句生成代码将使用此新指令。 移除了BEFORE_WITH
和BEFORE_ASYNC_WITH
指令。 (由 Mark Shannon 在 gh-120507 中贡献。)增加
POP_ITER
指令以支持 '虚拟' 迭代器。 (由 Mark Shannon 在 gh-132554 中贡献。)
伪指令¶
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_TRUE
和JUMP_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 asLOAD_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 中贡献。)
C API 中的新特性¶
增加
Py_PACK_VERSION()
和Py_PACK_FULL_VERSION()
,两个用于对 Python 版本号进行位打包操作的新宏。 这在比较Py_Version
或PY_VERSION_HEX
时很有用处。 (由 Petr Viktorin 在 gh-128629 中贡献。)新增
PyBytes_Join(sep, iterable)
函数,其功能类似于Python中的sep.join(iterable)
操作。(由Victor Stinner在 gh-121645 中贡献。)Add functions to manipulate the configuration of the current runtime Python interpreter (PEP 741: Python configuration C API):
(由 Victor Stinner 在 gh-107954 中贡献。)
Add functions to configure Python initialization (PEP 741: Python configuration C API):
(由 Victor Stinner 在 gh-107954 中贡献。)
增加
Py_fopen()
函数用于打开文件。 该函数功能类似于标准 Cfopen()
函数,但它接受一个 Python 对象作为 path 形参并会在出错时设置异常。 对应的新增函数Py_fclose()
函数应当用来关闭文件。 (由 Victor Stinner 在 gh-127350 中贡献。)新增
Py_HashBuffer()
函数用于计算并返回缓冲区的哈希值。(由 Antoine Pitrou 和 Victor Stinner 在 gh-122854 中贡献。)新增
PyImport_ImportModuleAttr()
和PyImport_ImportModuleAttrString()
辅助函数,用于导入模块并获取该模块的属性。(由 Victor Stinner 在 gh-128911 中贡献。)新增
PyIter_NextItem()
函数以替代返回值含义模糊的PyIter_Next()
函数。(由 Irit Katriel 和 Erlend Aasland 在 gh-105201 中贡献。)新增
PyLong_GetSign()
函数用于获取int
对象的符号位。(由 Sergey B Kirpichev 在 gh-116560 中贡献。)新增
PyLong_IsPositive()
、PyLong_IsNegative()
和PyLong_IsZero()
三个函数,分别用于检查PyLongObject
是否为正数、负数或零。(由 James Roy 和 Sergey B Kirpichev 在 gh-126061 中贡献。)新增用于在 C
<stdint.h>
数字类型与 Pythonint
对象之间进行转换的新函数:(由 Victor Stinner 在 gh-120389 中贡献。)
新增用于 Python
int
对象的导入导出API(参见 PEP 757):(由 Sergey B Kirpichev 和 Victor Stinner 在 gh-102471 中贡献。)
增加
PyMonitoring_FireBranchLeftEvent()
和PyMonitoring_FireBranchRightEvent()
分别用于生成BRANCH_LEFT
和BRANCH_RIGHT
事件。 (由 Mark Shannon 在 gh-122548 中贡献。)新增
PyType_Freeze()
函数用于将类型设为不可变。(由 Victor Stinner 在 gh-121654 中贡献。)增加
PyType_GetBaseByToken()
和Py_tp_token
槽位用于简化超类的标识,该特性尝试解决在 PEP 630 中提到的类型检查问题。 (在 gh-124153 中贡献。)新增
PyUnicode_Equal()
函数用于测试两个字符串是否相等。 此函数也被加入到受限 C API 中。 (由 Victor Stinner 在 gh-124502 中贡献。)新增
PyUnicodeWriter
API 用于创建 Pythonstr
对象,具有下列函数:(由 Victor Stinner 在 gh-119182 中贡献。)
在
PyArg_ParseTuple()
及相关函数中,k
和K
格式现在会优先使用__index__()
方法(如果可用),与其他整数格式的处理方式保持一致。(由 Serhiy Storchaka 在 gh-112068 中贡献。)在
Py_BuildValue()
中增加对新的p
格式单元的支持,它可根据 C 整数产生 Pythonbool
对象。 (由 Pablo Galindo 在 bpo-45325 中贡献。).)增加
PyUnstable_IsImmortal()
以确定一个对象是否为 immortal,用于调试目的。 (由 Peter Bierma 在 gh-128509 中贡献。)新增
PyUnstable_Object_EnableDeferredRefcount()
函数用于启用延迟引用计数功能,该功能如 PEP 703 所述。新增
PyUnstable_Object_IsUniquelyReferenced()
函数,作为 自由线程 构建环境下Py_REFCNT(op) == 1
的替代方案。(由 Peter Bierma 在 gh-133140 中贡献)增加
PyUnstable_Object_IsUniqueReferencedTemporary()
用于确定一个对象是否为解释器操作数栈上的唯一临时对象。 该函数在某些情况下可被用作通过检查Py_REFCNT()
是否为1
来判断作为参数传给 C API 函数的 Python 对象的替代方案。 (由 Sam Gross 在 gh-133164 中贡献。)
受限 C API 的变化¶
在受限 C API 3.14 及更新版本中,
Py_TYPE()
和Py_REFCNT()
现在被实现为不透明函数来隐藏实现细节。 (由 Victor Stinner 在 gh-120600 和 gh-124127 中贡献。)从受限 C API 移除了
PySequence_Fast_GET_SIZE
,PySequence_Fast_GET_ITEM
和PySequence_Fast_ITEMS
宏,因为它们在受限 C API 始终是不可用的。 (由 Victor Stinner 在 gh-91417 中贡献。)
被移除的 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_LIMIT
和PyThreadState.c_recursion_remaining
。 它们在 3.13 中增加并且未宣布弃用即被移除。 请在 C 代码中使用Py_EnterRecursiveCall()
来防范无限递归问题。 (由 Petr Viktorin 在 gh-133079 中移除,另请参阅 gh-130396。)
已弃用的 C API¶
现在
Py_HUGE_VAL
宏已被设为 soft deprecated。 请改用Py_INFINITY
。 (由 Sergey B Kirpichev 在 gh-120026 中贡献。)现在
Py_IS_NAN
,Py_IS_INFINITY
和Py_IS_FINITE
等宏已被设为 soft deprecated。 请改用isnan
,isinf
和isfinite
,它们自 C99 起在math.h
中可用。 (由 Sergey B Kirpichev 在 gh-119613 中贡献。)非元组序列当 items 包含存储 借入缓冲区 或 borrowed reference 的格式单元的情况下在
PyArg_ParseTuple()
和其他 参数解析 函数中用作(items)
格式单元参数的做法现在已被弃用。 (由 Serhiy Storchaka 在 gh-50333 中贡献。)现在
_PyMonitoring_FireBranchEvent
函数已被弃用并应当替换为对PyMonitoring_FireBranchLeftEvent()
和PyMonitoring_FireBranchRightEvent()
的调用。之前未写入文档的函数
PySequence_In()
现在被设为 soft deprecated。 请改用PySequence_Contains()
。 (由 Yuki Kobayashi 在 gh-127896 中贡献。)
计划在 Python 3.15 中移除¶
The
PyImport_ImportModuleNoBlock()
: UsePyImport_ImportModule()
instead.PyWeakref_GetObject()
andPyWeakref_GET_OBJECT()
: UsePyWeakref_GetRef()
instead. The pythoncapi-compat project can be used to getPyWeakref_GetRef()
on Python 3.12 and older.Py_UNICODE
类型和Py_UNICODE_WIDE
宏:改用wchar_t
。PyUnicode_AsDecodedObject()
: 改用PyCodec_Decode()
。PyUnicode_AsDecodedUnicode()
: 改用PyCodec_Decode()
;请注意某些编解码器 (例如 "base64") 可能返回str
以外的类型,比如bytes
。PyUnicode_AsEncodedObject()
: 改用PyCodec_Encode()
。PyUnicode_AsEncodedUnicode()
: 使用PyCodec_Encode()
代替;请注意,某些编解码器(如 "base64")可能返回bytes
之外的类型,如str
。Python 初始化函数, Python 3.13 中弃用:
Py_GetPath()
: UsePyConfig_Get("module_search_paths")
(sys.path
) instead.Py_GetPrefix()
: UsePyConfig_Get("base_prefix")
(sys.base_prefix
) instead. UsePyConfig_Get("prefix")
(sys.prefix
) if virtual environments need to be handled.Py_GetExecPrefix()
: UsePyConfig_Get("base_exec_prefix")
(sys.base_exec_prefix
) instead. UsePyConfig_Get("exec_prefix")
(sys.exec_prefix
) if virtual environments need to be handled.Py_GetProgramFullPath()
: UsePyConfig_Get("executable")
(sys.executable
) instead.Py_GetProgramName()
: UsePyConfig_Get("executable")
(sys.executable
) instead.Py_GetPythonHome()
: UsePyConfig_Get("home")
or thePYTHONHOME
environment variable instead.
在 Python 3.13 和更旧的版本中可以使用 pythoncapi-compat 项目 来获取
PyConfig_Get()
。用于配置 Python 的初始化的函数,在 Python 3.11 中已弃用:
PySys_SetArgvEx()
: 改为设置PyConfig.argv
。PySys_SetArgv()
: 改为设置PyConfig.argv
。Py_SetProgramName()
: 改为设置PyConfig.program_name
。Py_SetPythonHome()
: 改为设置PyConfig.home
。PySys_ResetWarnOptions()
: Clearsys.warnoptions
andwarnings.filters
instead.
Py_InitializeFromConfig()
API 应与PyConfig
一起使用。全局配置变量:
Py_DebugFlag
: 改用PyConfig.parser_debug
或PyConfig_Get("parser_debug")
。Py_VerboseFlag
: 改用PyConfig.verbose
或PyConfig_Get("verbose")
。Py_InteractiveFlag
: 改用PyConfig.interactive
或PyConfig_Get("interactive")
。Py_InspectFlag
: 改用PyConfig.inspect
或PyConfig_Get("inspect")
。Py_OptimizeFlag
: 改用PyConfig.optimization_level
或PyConfig_Get("optimization_level")
。Py_NoSiteFlag
: 改用PyConfig.site_import
或PyConfig_Get("site_import")
。Py_BytesWarningFlag
: 改用PyConfig.bytes_warning
或PyConfig_Get("bytes_warning")
。Py_FrozenFlag
: 使用PyConfig.pathconfig_warnings
或PyConfig_Get("pathconfig_warnings")
代替。Py_IgnoreEnvironmentFlag
: 使用PyConfig.use_environment
或PyConfig_Get("use_environment")
代替。Py_DontWriteBytecodeFlag
: 使用PyConfig.write_bytecode
或PyConfig_Get("write_bytecode")
代替。Py_NoUserSiteDirectory
: 使用PyConfig.user_site_directory
或PyConfig_Get("user_site_directory")
代替。Py_UnbufferedStdioFlag
: 使用PyConfig.buffered_stdio
或PyConfig_Get("buffered_stdio")
代替。Py_HashRandomizationFlag
: 使用PyConfig.use_hash_seed
和PyConfig.hash_seed
或PyConfig_Get("hash_seed")
代替。Py_IsolatedFlag
: 使用PyConfig.isolated
或PyConfig_Get("isolated")
代替。Py_LegacyWindowsFSEncodingFlag
: 使用PyPreConfig.legacy_windows_fs_encoding
或PyConfig_Get("legacy_windows_fs_encoding")
代替。Py_LegacyWindowsStdioFlag
: 使用PyConfig.legacy_windows_stdio
或PyConfig_Get("legacy_windows_stdio")
代替。Py_FileSystemDefaultEncoding
,Py_HasFileSystemDefaultEncoding
: 使用PyConfig.filesystem_encoding
或PyConfig_Get("filesystem_encoding")
代替。Py_FileSystemDefaultEncodeErrors
: 使用PyConfig.filesystem_errors
或PyConfig_Get("filesystem_errors")
代替。Py_UTF8Mode
: 使用PyPreConfig.utf8_mode
或PyConfig_Get("utf8_mode")
代替。 (参见Py_PreInitialize()
)。
Py_InitializeFromConfig()
API 应与PyConfig
一起使用,以设置这些选项。或者使用PyConfig_Get()
在运行时获取这些选项。
计划在 Python 3.16 中移除¶
捆绑的
libmpdec
副本。
计划在 Python 3.18 中移除¶
以下私有函数已被弃用,并计划在 Python 3.18 中移除:
_PyBytes_Join()
:使用PyBytes_Join()
。_PyDict_GetItemStringWithError()
: 使用PyDict_GetItemStringRef()
。_PyDict_Pop()
: 使用PyDict_Pop()
._PyLong_Sign()
:使用PyLong_GetSign()
。_PyLong_FromDigits()
和_PyLong_New()
:使用PyLongWriter_Create()
._PyThreadState_UncheckedGet()
:使用PyThreadState_GetUnchecked()
。_PyUnicode_AsString()
:使用PyUnicode_AsUTF8()
。_PyUnicodeWriter_Init()
: 将_PyUnicodeWriter_Init(&writer)
替换为writer = PyUnicodeWriter_Create(0)
。_PyUnicodeWriter_Finish()
: 将_PyUnicodeWriter_Finish(&writer)
替换为PyUnicodeWriter_Finish(writer)
。_PyUnicodeWriter_Dealloc()
: 将_PyUnicodeWriter_Dealloc(&writer)
替换为PyUnicodeWriter_Discard(writer)
。_PyUnicodeWriter_WriteChar()
: 将_PyUnicodeWriter_WriteChar(&writer, ch)
替换为PyUnicodeWriter_WriteChar(writer, ch)
._PyUnicodeWriter_WriteStr()
: 将_PyUnicodeWriter_WriteStr(&writer, str)
替换为PyUnicodeWriter_WriteStr(writer, str)
。_PyUnicodeWriter_WriteSubstring()
: 将_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)
替换为PyUnicodeWriter_WriteSubstring(writer, str, start, end)
。_PyUnicodeWriter_WriteASCIIString()
: 请将_PyUnicodeWriter_WriteASCIIString(&writer, str)
替换为PyUnicodeWriter_WriteASCII(writer, str)
。_PyUnicodeWriter_WriteLatin1String()
: 将_PyUnicodeWriter_WriteLatin1String(&writer, str)
替换为PyUnicodeWriter_WriteUTF8(writer, str)
。_PyUnicodeWriter_Prepare()
: (无替代)。_PyUnicodeWriter_PrepareKind()
: (无替代)。_Py_HashPointer()
:使用Py_HashPointer()
。_Py_fopen_obj()
:使用Py_fopen()
。
pythoncapi-compat 项目 可被用于在 Python 3.13 及更早版本中获取这些新的公有函数。 (由 Victor Stinner 在 gh-128863 中贡献。)
计划在未来版本中移除¶
以下 API 已被弃用,将被移除,但目前尚未确定移除日期。
Py_TPFLAGS_HAVE_FINALIZE
: 自 Python 3.8 起不再需要。PySlice_GetIndicesEx()
: 改用PySlice_Unpack()
andPySlice_AdjustIndices()
。PyUnicode_READY()
: 自 Python 3.12 起不再需要PyErr_Display()
: 改用PyErr_DisplayException()
。_PyErr_ChainExceptions()
: 改用_PyErr_ChainExceptions1()
。PyBytesObject.ob_shash
成员:改为调用PyObject_Hash()
。线程本地存储 (TLS) 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
, andfcntl
, 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-127146、gh-127683 和 gh-136931 中贡献。)现在可以通过 Py_NO_LINK_LIB 关闭基于
#pragma
与python3*.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 应用程序现在可配置为将
stdout
和stderr
输出内容重定向至系统日志。(由 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编译功能。
如遇任何错误或严重性能退化问题,请务必提交报告!
参见
移植到 Python 3.14¶
本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.
Python API 的变化¶
On Unix platforms other than macOS, forkserver is now the default start method for
multiprocessing
andProcessPoolExecutor
, instead of fork.如果你在
multiprocessing
或concurrent.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 with1
on failure instead of0
and2
on incorrect command-line parameters instead of1
. 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 649 和 PEP 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 中贡献)
解释器在将对象加载到操作数栈时,会通过尽可能 借用 引用来避免部分引用计数的修改。 这可能导致引用计数值比先前 Python 版本更小。 之前通过检查
Py_REFCNT()
是否为1
来判断函数参数是否未被其他代码引用的 C 扩展 API,现在应改用更安全的替代方案PyUnstable_Object_IsUniqueReferencedTemporary()
。以下私有函数已提升为公开 C API:
_PyBytes_Join()
:PyBytes_Join()
_PyLong_IsNegative()
:PyLong_IsNegative()
_PyLong_IsPositive()
:PyLong_IsPositive()
_PyLong_IsZero()
:PyLong_IsZero()
_PyLong_Sign()
:PyLong_GetSign()
_PyUnicodeWriter_Dealloc()
:PyUnicodeWriter_Discard()
_PyUnicodeWriter_Finish()
:PyUnicodeWriter_Finish()
_PyUnicodeWriter_Init()
: 使用PyUnicodeWriter_Create()
_PyUnicodeWriter_Prepare()
: (无替代)_PyUnicodeWriter_PrepareKind()
: (无替代)_PyUnicodeWriter_WriteChar()
:PyUnicodeWriter_WriteChar()
_PyUnicodeWriter_WriteStr()
:PyUnicodeWriter_WriteStr()
_PyUnicodeWriter_WriteSubstring()
:PyUnicodeWriter_WriteSubstring()
_PyUnicode_EQ()
:PyUnicode_Equal()
_PyUnicode_Equal()
:PyUnicode_Equal()
_Py_GetConfig()
:PyConfig_Get()
和PyConfig_GetInt()
_Py_HashBytes()
:Py_HashBuffer()
_Py_fopen_obj()
:Py_fopen()
PyMutex_IsLocked()
:PyMutex_IsLocked()
在 Python 3.13 和更早的版本中可以使用 pythoncapi-compat project 来充分利用这些新函数。