unittest
增加了 --durations
命令行选项,显示 N 个最慢的测试用例:
- python3 -m unittest --durations=3 lib.tests.test_threading
- .....
- Slowest test durations
- ----------------------------------------------------------------------
- 1.210s test_timeout (Lib.test.test_threading.BarrierTests)
- 1.003s test_default_timeout (Lib.test.test_threading.BarrierTests)
- 0.518s test_timeout (Lib.test.test_threading.EventTests)
- (0.000 durations hidden. Use -v to show these durations.)
- ----------------------------------------------------------------------
- Ran 158 tests in 9.869s
- OK (skipped=3)
(由 Giampaolo Rodola 在 gh-48330 [https://github.com/python/cpython/issues/48330] 中贡献。)
uuid
- 增加了一个 命令行接口。 (由 Adam Chhina 在 gh-88597 [https://github.com/python/cpython/issues/88597] 中贡献。)
性能优化
从 Unicode 对象中移除了
wstr
和wstr_length
成员。 这使得对象大小在 64 位平台上减少了 8 个或 16 个字节。 ( PEP 623 [https://peps.python.org/pep-0623/]) (由 Inada Naoki 在 gh-92536 [https://github.com/python/cpython/issues/92536] 中贡献。)增加了在构建进程中使用 BOLT 二进制优化器的实验性支持,这将使得性能提升 1-5%。 (由 Kevin Modzelewski 在 gh-90536 [https://github.com/python/cpython/issues/90536] 中贡献并由 Donghee Na 在 gh-101525 [https://github.com/python/cpython/issues/101525] 中微调。 )
对于包含分组引用的替换字符串的正则表达式替换(包括
re.sub()
和re.subn()
函数及对应的re.Pattern
方法)可加速 2—3 倍。 (由 Serhiy Storchaka 在 gh-91524 [https://github.com/python/cpython/issues/91524] 中贡献。)通过推迟高消耗的字符串格式化来加速
asyncio.Task
的创建的。 (由 Itamar Oren 在 gh-103793 [https://github.com/python/cpython/issues/103793] 中贡献。)作为在
tokenize
模块中应用 PEP 701 [https://peps.python.org/pep-0701/] 所要求的更改的附带效果,tokenize.tokenize()
和tokenize.generate_tokens()
函数可加速至多 64%。 (由 Marta Gómez Macías 和 Pablo Galindo 在 gh-102856 [https://github.com/python/cpython/issues/102856] 中贡献。)通过新的
LOAD_SUPER_ATTR
指令加速super()
方法调用和属性加载。 (由 Carl Meyer 和 Vladimir Matveev 在 gh-103497 [https://github.com/python/cpython/issues/103497] 中贡献。)
CPython 字节码的改变
移除了
LOAD_METHOD
指令。 它已被合并至LOAD_ATTR
。 现在如果设置了LOAD_ATTR
的 oparg 比特位则它的行为将类似原来的LOAD_METHOD
。 (由 Ken Jin 在 gh-93429 [https://github.com/python/cpython/issues/93429] 中贡献。)移除了
JUMP_IF_FALSE_OR_POP
和JUMP_IF_TRUE_OR_POP
指令。 (由 Irit Katriel 在 gh-102859 [https://github.com/python/cpython/issues/102859] 中贡献。)移除了
PRECALL
指令。 (由 Mark Shannon 在 gh-92925 [https://github.com/python/cpython/issues/92925] 中贡献。)添加了
BINARY_SLICE
和STORE_SLICE
指令。 (由 Mark Shannon 在 gh-94163 [https://github.com/python/cpython/issues/94163] 中贡献。)添加了
CALL_INTRINSIC_1
指令。 (由 Mark Shannon 在 gh-99005 [https://github.com/python/cpython/issues/99005] 中贡献。)添加了
CALL_INTRINSIC_2
指令。 (由 Irit Katriel 在 gh-101799 [https://github.com/python/cpython/issues/101799] 中贡献。)添加了
CLEANUP_THROW
指令。 (由 Brandt Bucher 在 gh-90997 [https://github.com/python/cpython/issues/90997] 中贡献。)添加了
END_SEND
指令。 (由 Mark Shannon 在 gh-103082 [https://github.com/python/cpython/issues/103082] 中贡献。)增加了
LOAD_FAST_AND_CLEAR
指令作为 PEP 709 [https://peps.python.org/pep-0709/] 的实现的组成部分。 (由 Carl Meyer 在 gh-101441 [https://github.com/python/cpython/issues/101441] 中贡献。)添加了
LOAD_FAST_CHECK
指令。 (由 Dennis Sweeney 在 gh-93143 [https://github.com/python/cpython/issues/93143] 中贡献。)增加了
LOAD_FROM_DICT_OR_DEREF
,LOAD_FROM_DICT_OR_GLOBALS
和LOAD_LOCALS
操作码作为 PEP 695 [https://peps.python.org/pep-0695/] 的组成部分。 移除了LOAD_CLASSDEREF
操作码,它可以用LOAD_LOCALS
加LOAD_FROM_DICT_OR_DEREF
来代替。 (由 Jelle Zijlstra 在 gh-103764 [https://github.com/python/cpython/issues/103764] 中贡献。)增加了
LOAD_SUPER_ATTR
指令。 (由 Carl Meyer 和 Vladimir Matveev 在 gh-103497 [https://github.com/python/cpython/issues/103497] 中贡献。)添加了
RETURN_CONST
指令。 (由 Wenyang Wang 在 gh-101632 [https://github.com/python/cpython/issues/101632] 中贡献。)
演示和工具
移除了包含旧演示脚本的
Tools/demo/
目录。 其副本可在 old-demos project [https://github.com/gvanrossum/old-demos] 中找到。 (由 Victor Stinner 在 gh-97681 [https://github.com/python/cpython/issues/97681] 中贡献。)移除了
Tools/scripts/
目录下过时的示例脚本。 其副本可在 old-demos project [https://github.com/gvanrossum/old-demos] 中找到。 (由 Victor Stinner 在 gh-97669 [https://github.com/python/cpython/issues/97669] 中贡献。)
弃用
argparse
:argparse.BooleanOptionalAction
的 type, choices 和 metavar 形参已被弃用并将在 3.14 中移除。 (由 Nikita Sobolev 在 gh-92248 [https://github.com/python/cpython/issues/92248] 中贡献。)ast
: 以下ast
特性自 Python 3.8 起已在文档中声明弃用,现在当运行时如果它们被访问或使用将发出DeprecationWarning
,并将在 Python 3.14 中移除:ast.Num
ast.Str
ast.Bytes
ast.NameConstant
ast.Ellipsis
请改用 ast.Constant
。 (由 Serhiy Storchaka 在 gh-90953 [https://github.com/python/cpython/issues/90953] 中贡献。)
-
子监视器类
asyncio.MultiLoopChildWatcher
,asyncio.FastChildWatcher
,asyncio.AbstractChildWatcher
和asyncio.SafeChildWatcher
已被弃用并将在 Python 3.14 中移除。 (由 Kumar Aditya 在 gh-94597 [https://github.com/python/cpython/issues/94597] 中贡献。)asyncio.set_child_watcher()
、asyncio.get_child_watcher()
、asyncio.AbstractEventLoopPolicy.set_child_watcher()
和asyncio.AbstractEventLoopPolicy.get_child_watcher()
已弃用,并将在 Python 3.14 中移除。(由 Kumar Aditya 在 gh-94597 [https://github.com/python/cpython/issues/94597] 中贡献。)现在默认事件循环策略的
get_event_loop()
方法在当前事件循环未设置并决定创建一个时将发出DeprecationWarning
。 (由 Serhiy Storchaka 和 Guido van Rossum 在 gh-100160 [https://github.com/python/cpython/issues/100160] 中贡献。)
calendar
:calendar.January
和calendar.February
常量已被弃用并由calendar.JANUARY
和calendar.FEBRUARY
替代。 (由 Prince Roshan 在 gh-103636 [https://github.com/python/cpython/issues/103636] 中贡献。)collections.abc
: 已弃用collections.abc.ByteString
。 推荐改用Sequence
或collections.abc.Buffer
。 在类型标中,推荐改用并集,如bytes | bytearray
或collections.abc.Buffer
。 (由 Shantanu Jain 在 gh-91896 [https://github.com/python/cpython/issues/91896] 中贡献。)datetime
:datetime.datetime
的utcnow()
和utcfromtimestamp()
已被弃用并将在未来的版本中移除。 请改用可感知时区的对象以 UTC 来表示日期时间:分别调用now()
和fromtimestamp()
并设置 tz 形参为datetime.UTC
。 (由 Paul Ganssle 在 gh-103857 [https://github.com/python/cpython/issues/103857] 中贡献。)email
: 已弃用email.utils.localtime()
中的 isdst 形参。 (由 Alan Williams 在 gh-72346 [https://github.com/python/cpython/issues/72346] 中贡献。)importlib.abc
: 已弃用下列类,计划在 Python 3.14 中移除:importlib.abc.ResourceReader
importlib.abc.Traversable
importlib.abc.TraversableResources
使用 importlib.resources.abc
类代替:
(由 Jason R. Coombs 和 Hugo van Kemenade 在 gh-93963 [https://github.com/python/cpython/issues/93963] 中贡献。)
itertools
: 已弃用对 copy、deepcopy 和 pickle 操作的支持,它们未被写入文档、效率低下、历史上充满问题且缺乏一致性。 这将在 3.14 中移除以显著减少代码量和维护负担。 (由 Raymond Hettinger 在 gh-101588 [https://github.com/python/cpython/issues/101588] 中贡献。)multiprocessing
: 在 Python 3.14 中,默认的multiprocessing
启动方法将在 Linux、BSD 和其他非 macOS 的 POSIX 平台上改为更安全的方法,在这些平台上目前默认为'fork'
(gh-84559 [https://github.com/python/cpython/issues/84559])。 在运行时添加相关警告被认为干扰性太大因为大部分代码都不会在意这个问题。 当你的代码 需要'fork'
时请使用get_context()
或set_start_method()
API 显式地指明。 参见 上下文和启动方法。pkgutil
:pkgutil.find_loader()
和pkgutil.get_loader()
已被弃用并将在 Python 3.14 中移除;请改用importlib.util.find_spec()
。 (由 Nikita Sobolev 在 gh-97850 [https://github.com/python/cpython/issues/97850] 中贡献。)pty
: 该模块有两个未写入文档的master_open()
和slave_open()
函数自 Python 2 起即已被弃用但直到 3.12 才添加了相应的DeprecationWarning
。 它们将在 3.14 中移除。 (由 Soumendra Ganguly 和 Gregory P. Smith 在 gh-85984 [https://github.com/python/cpython/issues/85984] 中贡献。).)os
:在 Windows 上由
os.stat()
和os.lstat()
返回的st_ctime
字段已被弃用。 在未来的发布版中,它们将包含最近的元数据修改时间,以与其他平台保持一致。 目前,它们仍然包含创建时间,该值也可通过新的st_birthtime
字段获取。 (由 Steve Dower 在 gh-99726 [https://github.com/python/cpython/issues/99726] 中贡献。)在 POSIX 平台上,当
os.fork()
能检测到被多线程的进程调用时现在会引发DeprecationWarning
。 当在 POSIX 平台上这样做时总是会存在基础性的不兼容。 即使这样的代码 appeared 看起来有效。 我们添加该警告是为了引起注意,因为这种做法遇到的问题越来越频繁。 请参阅os.fork()
文档了解详情并查看 这个关于 fork 与线程不兼容问题的讨论 [https://discuss.python.org/t/concerns-regarding-deprecation-of-fork-with-alive-threads/33555] 以了解 为什么 现在我们要向开发者揭示这一长期存在的平台兼容性问题。
当由于使用 multiprocessing
或 concurrent.futures
而出现此警告时的解决办法是使用其他的 multiprocessing
启动方法如 "spawn"
或 "forkserver"
。
shutil
:shutil.rmtree()
的 onerror 参数已被弃用;请改用 onexc。 (由 Irit Katriel 在 gh-102828 [https://github.com/python/cpython/issues/102828] 中贡献。)-
默认适配器和转换器 现在已被弃用,请使用 适配器和转换器范例程序 并根据你的需要调整它们。 (由 Erlend E. Aasland 在 gh-90016 [https://github.com/python/cpython/issues/90016] 中贡献。)
在
execute()
中,现在当 命名占位符 与作为 sequence 而不是dict
提供的形参一起使用时将发出DeprecationWarning
。 从 Python 3.14 开始,当命名占位符与作为序列提供的形参一起使用时将引发ProgrammingError
。 (由 Erlend E. Aasland 在 gh-101698 [https://github.com/python/cpython/issues/101698] 中贡献。)
sys
:sys.last_type
,sys.last_value
和sys.last_traceback
字段已被弃用。 请改用sys.last_exc
。 (由 Irit Katriel 在 gh-102778 [https://github.com/python/cpython/issues/102778] 中贡献。)tarfile
: 提取 tar 归档而不指定 filter 的做法已被弃用直到 Python 3.14,在该版本中'data'
将成为默认过滤器。 请参阅 解压缩过滤器 了解详情。-
typing.Hashable
和typing.Sized
,分别为collections.abc.Hashable
和collections.abc.Sized
的别名,现已被弃用。 (gh-94309 [https://github.com/python/cpython/issues/94309]。)typing.ByteString
自 Python 3.9 起已被弃用,现在当被使用时将会发出DeprecationWarning
。 (由 Alex Waygood 在 gh-91896 [https://github.com/python/cpython/issues/91896] 中贡献。)
xml.etree.ElementTree
: 现在该模块在对xml.etree.ElementTree.Element
执行真值测试时将发出DeprecationWarning
。 在之前,Python 实现会发出FutureWarning
,而 C 实现则不会发出任何警告。 (由 Jacob Walls 在 gh-83122 [https://github.com/python/cpython/issues/83122] 中贡献。)coroutine throw()
,generator throw()
和async generator throw()
的三参数签名形式 (type, value, traceback) 已被弃用并可能在未来的 Python 版本中移除。 请改用这些函数的单参数版本。 (由 Ofey Chan 在 gh-89874 [https://github.com/python/cpython/issues/89874] 中贡献。)现在当一个模块的
__package__
不同于__spec__.parent
时将引发DeprecationWarning
(在之前版本中则为ImportWarning
)。 (由 Brett Cannon 在 gh-65961 [https://github.com/python/cpython/issues/65961] 中贡献。)在模块上设置
__package__
或__cached__
的做法已被弃用,并且在 Python 3.14 中将不会再被设置或是被导入系统纳入考虑。 (由 Brett Cannon 在 gh-65961 [https://github.com/python/cpython/issues/65961] 中贡献。)对布尔值的按位取反运算符 (
~
) 已被弃用。 它在 Python 3.16 中将抛出错误。 请改用not
来执行布尔值的逻辑非运算。 在你确实需要对下层的int
执行按位取反运算的少数场景下,请显式地将其转换为整数值:~int(x)
。 (由 Tim Hoffmann 在 gh-103487 [https://github.com/python/cpython/issues/103487] 中贡献。)在代码对象上访问
co_lnotab
的做法在 Python 3.10 中已根据 PEP 626 [https://peps.python.org/pep-0626/] 被弃用,但直到在 3.12 中才添加了适当的DeprecationWarning
。 可能会在 3.15 中移除。 (由 Nikita Sobolev 在 gh-101866 [https://github.com/python/cpython/issues/101866] 中贡献。)
计划在 Python 3.13 中移除
模块 (参见 PEP 594 [https://peps.python.org/pep-0594/]):
aifc
audioop
cgi
cgitb
chunk
crypt
imghdr
mailcap
msilib
nis
nntplib
ossaudiodev
pipes
sndhdr
spwd
sunau
telnetlib
uu
xdrlib
其他模块:
lib2to3
,以及 2to3 程序 (gh-84540 [https://github.com/python/cpython/issues/84540])
API:
configparser.LegacyInterpolation
(gh-90765 [https://github.com/python/cpython/issues/90765])locale.resetlocale()
(gh-90817 [https://github.com/python/cpython/issues/90817])turtle.RawTurtle.settiltangle()
(gh-50096 [https://github.com/python/cpython/issues/50096])unittest.findTestCases()
(gh-50096 [https://github.com/python/cpython/issues/50096])unittest.getTestCaseNames()
(gh-50096 [https://github.com/python/cpython/issues/50096])unittest.makeSuite()
(gh-50096 [https://github.com/python/cpython/issues/50096])unittest.TestProgram.usageExit()
(gh-67048 [https://github.com/python/cpython/issues/67048])webbrowser.MacOSX
(gh-86421 [https://github.com/python/cpython/issues/86421])classmethod
描述器串联 (gh-89519 [https://github.com/python/cpython/issues/89519])importlib.resources
中已弃用的方法:contents()
is_resource()
open_binary()
open_text()
path()
read_binary()
read_text()
改用 importlib.resources.files()
。 参见 importlib-resources: Migrating from Legacy [https://importlib-resources.readthedocs.io/en/latest/using.html#migrating-from-legacy] (gh-106531 [https://github.com/python/cpython/issues/106531])
计划在 Python 3.14 中移除
argparse
:argparse.BooleanOptionalAction
的 type, choices 和 metavar 形参已被弃用并将在 3.14 中移除。 (由 Nikita Sobolev 在 gh-92248 [https://github.com/python/cpython/issues/92248] 中贡献。)ast
: 以下特性自 Python 3.8 起已在文档中声明弃用,现在当运行时如果它们被访问或使用时将发出DeprecationWarning
,并将在 Python 3.14 中移除:ast.Num
ast.Str
ast.Bytes
ast.NameConstant
ast.Ellipsis
请改用 ast.Constant
。 (由 Serhiy Storchaka 在 gh-90953 [https://github.com/python/cpython/issues/90953] 中贡献。)
-
子监视器类
MultiLoopChildWatcher
,FastChildWatcher
,AbstractChildWatcher
和SafeChildWatcher
已被弃用并将在 Python 3.14 中移除。 (由 Kumar Aditya 在 gh-94597 [https://github.com/python/cpython/issues/94597] 中贡献。)asyncio.set_child_watcher()
、asyncio.get_child_watcher()
、asyncio.AbstractEventLoopPolicy.set_child_watcher()
和asyncio.AbstractEventLoopPolicy.get_child_watcher()
已弃用,并将在 Python 3.14 中移除。(由 Kumar Aditya 在 gh-94597 [https://github.com/python/cpython/issues/94597] 中贡献。)现在默认事件循环策略的
get_event_loop()
方法在当前事件循环未设置并决定创建一个时将发出DeprecationWarning
。 (由 Serhiy Storchaka 和 Guido van Rossum 在 gh-100160 [https://github.com/python/cpython/issues/100160] 中贡献。)
collections.abc
: 已弃用ByteString
。 推荐改用Sequence
或Buffer
。 用于类型标注时,则推荐并集运算符,如bytes | bytearray
,或collections.abc.Buffer
。 (由 Shantanu Jain 在 gh-91896 [https://github.com/python/cpython/issues/91896] 中贡献。)email
: 已弃用email.utils.localtime()
中的 isdst 形参。 (由 Alan Williams 在 gh-72346 [https://github.com/python/cpython/issues/72346] 中贡献。)importlib.abc
中已弃用的类:importlib.abc.ResourceReader
importlib.abc.Traversable
importlib.abc.TraversableResources
使用 importlib.resources.abc
类代替:
(由 Jason R. Coombs 和 Hugo van Kemenade 在 gh-93963 [https://github.com/python/cpython/issues/93963] 中贡献。)
itertools
具有对 copy, deepcopy 和 pickle 等操作的未写入文档的、低效的、历史上充满问题的且不稳定的支持。 这将在 3.14 中移除以显著减少代码量和维护负担。 (由 Raymond Hettinger 在 gh-101588 [https://github.com/python/cpython/issues/101588] 中贡献。)multiprocessing
: 默认的启动方法在目前默认使用'fork'
的 Linux, BSD 和其他非 macOS POSIX 平台上将改为更安全的方法 (gh-84559 [https://github.com/python/cpython/issues/84559])。 为此添加运行时警告将带来糟糕的体验因为大部分代码并不会关心这个问题。 当你的代码 需要'fork'
时请使用get_context()
或set_start_method()
API 来显式地指明。 参见 上下文和启动方法。pathlib
:is_relative_to()
和relative_to()
: 传入额外参数的做法已被弃用。pkgutil
: 现在find_loader()
和get_loader()
将引发DeprecationWarning
;请改用importlib.util.find_spec()
。 (由 Nikita Sobolev 在 gh-97850 [https://github.com/python/cpython/issues/97850] 中贡献。)pty
:master_open()
: 使用pty.openpty()
。slave_open()
: 使用pty.openpty()
。
-
如果使用了 命名占位符 且 parameters 是一个序列而不是
dict
则选择execute()
和executemany()
。
typing
:ByteString
自 Python 3.9 起已被弃用,现在当被使用时将会发出DeprecationWarning
。urllib
:urllib.parse.Quoter
已被弃用:它不应被作为公有 API。 (由 Gregory P. Smith 在 gh-88168 [https://github.com/python/cpython/issues/88168] 中贡献。)
Python 3.15 中的待移除功能
导入系统:
当设置
__spec__.cached
失败时在模块上设置__cached__
的做法已被弃用。 在 Python 3.15 中,__cached__
将不会再被导入系统或标准库纳入考虑。 (gh-97879 [https://github.com/python/cpython/issues/97879])当设备
__spec__.parent
失败时在模块上设置__package__
的做法已被弃用。 在 Python 3.15 中,__package__
将不会再被导入系统或标准库纳入考虑。 (gh-97879 [https://github.com/python/cpython/issues/97879])
-
- 未写入文档的
ctypes.SetPointerType()
函数自 Python 3.13 起已被弃用。
- 未写入文档的
-
过时且很少被使用的
CGIHTTPRequestHandler
自 Python 3.13 起已被弃用。 不存在直接的替代品。 对于建立带有请求处理器的 Web 服务程序来说 任何东西 都比 CGI 要好。用于 python -m http.server 命令行界面的
--cgi
旗标自 Python 3.13 起已被弃用。
-
getdefaultlocale()
函数自 Python 3.11 起已被弃用。 最初计划在 Python 3.13 中移除它 (gh-90817 [https://github.com/python/cpython/issues/90817]),但已被推迟至 Python 3.15。 请改用getlocale()
,setlocale()
和getencoding()
。 (由 Hugo van Kemenade 在 gh-111187 [https://github.com/python/cpython/issues/111187] 中贡献。)
-
PurePath.is_reserved()
自 Python 3.13 起已被弃用。 请使用os.path.isreserved()
来检测 Windows 上的保留路径。
-
java_ver()
自 Python 3.13 起已被弃用。 此函数仅对 Jython 支持有用,具有令人困惑的 API,并且大部分未经测试。
-
- 在 Python 3.15 中
RLock()
将不再接受参数。 传入参数的做法自 Python 3.14 起已被弃用,因为 Python 版本不接受任何参数,而 C 版本允许任意数量的位置或关键字参数,但会忽略所有参数。
- 在 Python 3.15 中
-
types.CodeType
: 访问co_lnotab
的做法自 3.10 起已根据 PEP 626 [https://peps.python.org/pep-0626/] 被弃用并曾计划在 3.12 中移除,但在 3.12 中实际仅设置了DeprecationWarning
。 可能会在 3.15 中移除。 (由 Nikita Sobolev 在 gh-101866 [https://github.com/python/cpython/issues/101866] 中贡献。)
-
未写入文档的用于创建
NamedTuple
类的关键字参数语法 (例如Point = NamedTuple("Point", x=int, y=int)
) 自 Python 3.13 起已被弃用。 请改用基于类的语法或函数语法。typing.no_type_check_decorator()
装饰器自 Python 3.13 起已被弃用。 存在于typing
模块八年之后,它仍未被任何主要类型检查器所支持。
wave
:Wave_read
和Wave_write
类的getmark()
,setmark()
和getmarkers()
方法自 Python 3.13 起已被弃用。
计划在 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()
。 (由 Jiahao Li 和 Kumar Aditya 在 gh-122875 [https://github.com/python/cpython/issues/122875] 中贡献。)
-
- 对布尔类型
~True
或~False
执行按位取反的操作自 Python 3.12 起已被弃用,因为它会产生奇怪和不直观的结果 (-2
and-1
)。 请改用not x
来对布尔值执行逻辑否操作。 对于需要对下层整数执行按位取反操作的少数场合,请显式地将其转换为int
(~int(x)
)。
- 对布尔类型
-
ExecError
异常自 Python 3.14 起已被弃用。 它自 Python 3.4 起就未被shutil
中的任何函数所使用,现在是RuntimeError
的一个别名。
-
Class.get_methods
方法自 Python 3.14 起被弃用。
sys
:_enablelegacywindowsfsencoding()
函数自 Python 3.13 起被弃用。 请改用PYTHONLEGACYWINDOWSFSENCODING
环境变量。
-
- 未写入文档也未被使用的
TarFile.tarfile
属性自 Python 3.13 起被弃用。
- 未写入文档也未被使用的
计划在未来版本中移除
以下API将会被移除,尽管具体时间还未确定。
argparse
: 嵌套参数分组和嵌套互斥分组的做法已被弃用。array
的'u'
格式代码 (gh-57281 [https://github.com/python/cpython/issues/57281])-
bool(NotImplemented)
。生成器:
throw(type, exc, tb)
和athrow(type, exc, tb)
签名已被弃用:请改用throw(exc)
和athrow(exc)
,即单参数签名。目前 Python 接受数字类字面值后面紧跟关键字的写法,例如
0in x
,1or x
,0if 1else 2
。 它允许像[0x1for x in y]
这样令人困惑且有歧义的表达式 (它可以被解读为[0x1 for x in y]
或者[0x1f or x in y]
)。 如果数字类字面值后面紧跟关键字and
,else
,for
,if
,in
,is
和or
中的一个将会引发语法警告。 在未来的版本中它将改为语法错误。 (gh-87999 [https://github.com/python/cpython/issues/87999])对
__index__()
和__int__()
方法返回非 int 类型的支持:将要求这些方法必须返回int
的子类的实例。对
__complex__()
方法返回complex
的子类的支持:将要求这些方法必须返回complex
的实例。将
int()
委托给__trunc__()
方法。传入一个复数作为
complex()
构造器中的 real 或 imag 参数的做法现在已被弃用;它应当仅作为单个位置参数被传入。 (由 Serhiy Storchaka 在 gh-109218 [https://github.com/python/cpython/issues/109218] 中贡献。).)
calendar
:calendar.January
和calendar.February
常量已被弃用并由calendar.JANUARY
和calendar.FEBRUARY
替代。 (由 Prince Roshan 在 gh-103636 [https://github.com/python/cpython/issues/103636] 中贡献。)-
utcnow()
: 使用datetime.datetime.now(tz=datetime.UTC)
。utcfromtimestamp()
: 使用datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC)
。
gettext
: 复数值必须是一个整数。-
load_module()
方法:改用exec_module()
。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 [https://github.com/python/cpython/issues/91760] 中贡献。)sre_compile
,sre_constants
和sre_parse
模块。shutil
:rmtree()
的 onerror 形参在 Python 3.12 中已被弃用;请改用 onexc 形参。ssl
选项和协议:ssl.SSLContext
不带 protocol 参数的做法已被弃用。ssl.SSLContext
:set_npn_protocols()
和selected_npn_protocol()
已被弃用:请改用 ALPN。ssl.OP_NO_SSL*
选项ssl.OP_NO_TLS*
选项ssl.PROTOCOL_SSLv3
ssl.PROTOCOL_TLS
ssl.PROTOCOL_TLSv1
ssl.PROTOCOL_TLSv1_1
ssl.PROTOCOL_TLSv1_2
ssl.TLSVersion.SSLv3
ssl.TLSVersion.TLSv1
ssl.TLSVersion.TLSv1_1
sysconfig.is_python_build()
check_home 形参已被弃用并会被忽略。threading
的方法: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.Text
(gh-92332 [https://github.com/python/cpython/issues/92332])。unittest.IsolatedAsyncioTestCase
: 从测试用例返回不为None
的值的做法已被弃用。urllib.parse
函数已被弃用:改用urlparse()
splitattr()
splithost()
splitnport()
splitpasswd()
splitport()
splitquery()
splittag()
splittype()
splituser()
splitvalue()
to_bytes()
urllib.request
: 发起请求的URLopener
和FancyURLopener
方式已被弃用。 改用更新urlopen()
函数和方法。wsgiref
:SimpleHandler.stdout.write()
不应执行部分写入。xml.etree.ElementTree
: 对Element
的真值测试已被弃用。 在未来的发布版中它将始终返回True
。 建议改用显式的len(elem)
或elem is not None
测试。
移除
asynchat 和 asyncore
- 这两个模块已根据 PEP 594 [https://peps.python.org/pep-0594/] 中的时间表被移除,它们从 Python 3.6 起已被弃用。 请改用
asyncio
。 (由 Nikita Sobolev 在 gh-96580 [https://github.com/python/cpython/issues/96580] 中贡献。)
configparser
configparser
中的几个从 3.2 起已被弃用的名称已根据 gh-89336 [https://github.com/python/cpython/issues/89336] 被移除:configparser.ParsingError
不再具有filename
属性或参数。 请改用source
属性和参数。configparser
不再具有SafeConfigParser
类。 请改用更简短的名称ConfigParser
。configparser.ConfigParser
不再具有readfp
方法。 请改用read_file()
。
distutils
- 移除了
distutils
包。 它已在 Python 3.10 中根据 PEP 632 [https://peps.python.org/pep-0632/] "Deprecate distutils module" 被弃用。 对于仍然使用distutils
且无法升级为使用其他工具的项目,可以安装setuptools
项目:它仍然提供了distutils
。 (由 Victor Stinner 在 gh-92584 [https://github.com/python/cpython/issues/92584] 中贡献。)
ensurepip
pip (>= 22.1)
不再要求在环境中安装 setuptools。 基于 setuptools
(和基于 distutils
) 的包仍然可通过 pip install
来使用,因为 pip 将在它用于构建包的构建环境中提供 setuptools
。
在默认情况下由 venv
创建或通过 ensurepip
初始化的环境将不再提供 easy_install
, pkg_resources
, setuptools
和 distutils
包,因为它们是 setuptools
包的组成部分。 对于在运行时依赖这些包的项目,应当将 setuptools
项目声明为依赖项之一并单独安装(通常是使用 pip)。
(由 Pradyun Gedam 在 gh-95299 [https://github.com/python/cpython/issues/95299] 中贡献。)
enum
- 移除了
enum
的EnumMeta.__getattr__
,枚举属性访问已不再需要它。 (由 Ethan Furman 在 gh-95083 [https://github.com/python/cpython/issues/95083] 中贡献。)
ftplib
- 移除了
ftplib
的FTP_TLS.ssl_version
类属性:请改用 context 形参。 (由 Victor Stinner 在 gh-94172 [https://github.com/python/cpython/issues/94172] 中贡献。)
gzip
- 移除了
gzip
中gzip.GzipFile
的filename
属性,自 Python 2.6 起该属性已被弃用,请改用name
属性。 在可写模式下,如果filename
属性没有'.gz'
文件扩展名则会添加它。 (由 Victor Stinner 在 gh-94196 [https://github.com/python/cpython/issues/94196] 中贡献。)
hashlib
- 移除了
hashlib
中hashlib.pbkdf2_hmac()
的纯 Python 实现,它在 Python 3.10 中已被弃用。 Python 3.10 及更新版本需要 OpenSSL 1.1.1 ( PEP 644 [https://peps.python.org/pep-0644/]):该 OpenSSL 版本提供了pbkdf2_hmac()
的更快速的 C 实现。 (由 Victor Stinner 在 gh-94199 [https://github.com/python/cpython/issues/94199] 中贡献。)
importlib
importlib
中许多先前已弃用对象的清理工作现已完成:对
module_repr()
的引用以及支持已被移除。 (由 Barry Warsaw 在 gh-97850 [https://github.com/python/cpython/issues/97850] 中贡献。)importlib.util.set_package
,importlib.util.set_loader
和importlib.util.module_for_loader
均已被移除。 (由 Brett Cannon 和 Nikita Sobolev 在 gh-65961 [https://github.com/python/cpython/issues/65961] 和 gh-97850 [https://github.com/python/cpython/issues/97850] 中贡献。)对
find_loader()
和find_module()
API 的支持已被移除。 (由 Barry Warsaw 在 gh-98040 [https://github.com/python/cpython/issues/98040] 中贡献。)importlib.abc.Finder
,pkgutil.ImpImporter
和pkgutil.ImpLoader
已被移除。 (由 Barry Warsaw 在 gh-98040 [https://github.com/python/cpython/issues/98040] 中贡献。)
imp
imp
模块已被移除。 (由 Barry Warsaw 在 gh-98040 [https://github.com/python/cpython/issues/98040] 中贡献。)
要进行迁移,请参考以下对照表:
imp
importlib
imp.NullImporter
将
None
插入到sys.path_importer_cache
imp.cache_from_source()
imp.find_module()
imp.get_magic()
imp.get_suffixes()
importlib.machinery.SOURCE_SUFFIXES
,importlib.machinery.EXTENSION_SUFFIXES
和importlib.machinery.BYTECODE_SUFFIXES
imp.get_tag()
imp.load_module()
imp.new_module(name)
types.ModuleType(name)
imp.reload()
imp.source_from_cache()
imp.load_source()
见下文
将 imp.load_source()
替换为:
- import importlib.util
- import importlib.machinery
- def load_source(modname, filename):
- loader = importlib.machinery.SourceFileLoader(modname, filename)
- spec = importlib.util.spec_from_file_location(modname, filename, loader=loader)
- module = importlib.util.module_from_spec(spec)
- # 模块将总是被执行而不缓存在 sys.modules 中。
- # 取消对下一行的注释以缓存此模块。
- # sys.modules[module.__name__] = module
- loader.exec_module(module)
- return module
已移除
imp
的函数和属性并且没有替代选项:未写入文档的函数:
imp.init_builtin()
imp.load_compiled()
imp.load_dynamic()
imp.load_package()
imp.lock_held()
,imp.acquire_lock()
,imp.release_lock()
: 加锁方案在 Python 3.3 中已改为模块级锁。imp.find_module()
常量:SEARCH_ERROR
,PY_SOURCE
,PY_COMPILED
,C_EXTENSION
,PY_RESOURCE
,PKG_DIRECTORY
,C_BUILTIN
,PY_FROZEN
,PY_CODERESOURCE
,IMP_HOOK
。
io
- 移除了
io
中的io.OpenWrapper
和_pyio.OpenWrapper
,它们在 Python 3.10 中已被弃用:请改用open()
。open()
(io.open()
) 函数是一个内置函数。 自 Python 3.10 起,_pyio.open()
也是一个静态方法。 (由 Victor Stinner 在 gh-94169 [https://github.com/python/cpython/issues/94169] 中贡献。).)
locale
- 移除了
locale
的locale.format()
函数,它在 Python 3.7 中已被弃用:请改用locale.format_string()
。 (由 Victor Stinner 在 gh-94226 [https://github.com/python/cpython/issues/94226] 中贡献。)
smtpd
smtpd
模块已按照 PEP 594 [https://peps.python.org/pep-0594/] 中的计划表被移除,它在 Python 3.4.7 和 3.5.4 中已被弃用。 请改用 aiosmtpd [https://pypi.org/project/aiosmtpd/] PyPI 模块或任何其他基于asyncio
的服务器。 (由 Oleg Iarygin 在 gh-93243 [https://github.com/python/cpython/issues/93243] 中贡献。)
sqlite3
以下未写入文档的
sqlite3
特性,在 Python 3.10 中已被弃用,现在已被移除:sqlite3.enable_shared_cache()
sqlite3.OptimizedUnicode
如果必须使用共享缓存,请在以 URI 模式打开数据库时使用 cache=shared
查询参数。
sqlite3.OptimizedUnicode
文本工厂函数自 Python 3.3 起已成为 str
的一个别名。 之前将文本工厂设为 OptimizedUnicode
的代码可以显式地使用 str
,或者依赖同样为 str
的默认值。
(由 Erlend E. Aasland 在 gh-92548 [https://github.com/python/cpython/issues/92548] 中贡献。)
ssl
移除了
ssl
的ssl.RAND_pseudo_bytes()
函数,它在 Python 3.6 中已被弃用:请改用os.urandom()
或ssl.RAND_bytes()
。 (由 Victor Stinner 在 gh-94199 [https://github.com/python/cpython/issues/94199] 中贡献。)移除了
ssl.match_hostname()
函数。 它在 Python 3.7 中已被弃用。 OpenSSL 自 Python 3.7 起将会执行主机名匹配,Python 已不再使用ssl.match_hostname()
函数。 (由 Victor Stinner 在 gh-94199 [https://github.com/python/cpython/issues/94199] 中贡献。)移除了
ssl.wrap_socket()
函数,它在 Python 3.7 中已被弃用:应改为创建一个ssl.SSLContext
对象并调用其ssl.SSLContext.wrap_socket
方法。 任何仍然使用ssl.wrap_socket()
的包都是已不适用且不安全的。 该函数既不会发送 SNI TLS 扩展也不会验证服务器主机名。 其代码会受到 CWE 295 [https://cwe.mitre.org/data/definitions/295.html] (Improper Certificate Validation) 的影响。 (由 Victor Stinner 在 gh-94199 [https://github.com/python/cpython/issues/94199] 中贡献。)
unittest
已弃用的别名
方法名
弃用于
failUnless
3.1
failIf
3.1
failUnlessEqual
3.1
failIfEqual
3.1
failUnlessAlmostEqual
3.1
failIfAlmostEqual
3.1
failUnlessRaises
3.1
assert_
3.2
assertEquals
3.2
assertNotEquals
3.2
assertAlmostEquals
3.2
assertNotAlmostEquals
3.2
assertRegexpMatches
3.2
assertRaisesRegexp
3.2
assertNotRegexpMatches
3.5
您可以使用 https://github.com/isidentical/teyit 来自动更新你的单元测试。
未写入文档且已不可用的
TestCase
方法assertDictContainsSubset
。 (在 Python 3.2 中已弃用。)未写入文档的
TestLoader.loadTestsFromModule
形参 use_load_tests。 (自 Python 3.5 起已弃用并会被忽略。)TextTestResult
类的一个别名:_TextTestResult
。 (在 Python 3.2 中已弃用。)
(由 Serhiy Storchaka 在 gh-89325 [https://github.com/python/cpython/issues/89325] 中贡献。)
webbrowser
- 从
webbrowser
移除了对过时浏览器的支持。 被移除的浏览器包括:Grail、Mosaic、Netscape、Galeon、Skipstone、Iceape、Firebird 和 Firefox 35 及以下的版本 (gh-102871 [https://github.com/python/cpython/issues/102871])。
xml.etree.ElementTree
- 移除了纯 Python 实现的
ElementTree.Element.copy()
方法,该方法在 Python 3.10 中已被弃用,请改用copy.copy()
函数。xml.etree.ElementTree
的 C 实现没有copy()
方法,只有__copy__()
方法。 (由 Victor Stinner 在 gh-94383 [https://github.com/python/cpython/issues/94383] 中贡献。)
zipimport
- 移除了
zipimport
的find_loader()
和find_module()
方法,它们在 Python 3.10 中已被弃用:请改用find_spec()
方法。 请参阅 PEP 451 [https://peps.python.org/pep-0451/] 了解相关说明。 (由 Victor Stinner 在 gh-94379 [https://github.com/python/cpython/issues/94379] 中贡献。)
其他事项
从文档
Makefile
和Doc/tools/rstlint.py
中移除了suspicious
规则,请改用 sphinx-lint [https://github.com/sphinx-contrib/sphinx-lint]。 (由 Julien Palard 在 gh-98179 [https://github.com/python/cpython/issues/98179] 中贡献。)移除了
ftplib
、imaplib
、poplib
和smtplib
模块中的 keyfile 和 certfile 形参数,以及http.client
模块中的 key_file、cert_file 和 check_hostname 形参,它们自 Python 3.6 起都已被弃用。 请改用 context 形参(在imaplib
中为 ssl_context 形参)。 (由 Victor Stinner 在 gh-94172 [https://github.com/python/cpython/issues/94172] 中贡献。).)从多个标准库模块和测试中移除了
Jython
兼容性处理。 (由 Nikita Sobolev 在 gh-99482 [https://github.com/python/cpython/issues/99482] 中贡献。)从
ctypes
模块移除了usebroken_old_ctypes_structure_semantics_
旗标。 (由 Nikita Sobolev 在 gh-99285 [https://github.com/python/cpython/issues/99285] 中贡献。)
移植到 Python 3.12
本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.
Python API 的变化
现在对于正则表达式中的数字分组引用和分组名称将应用更严格的规则。 现在只接受 ASCII 数字序列作为数字引用。 字节串模式和替换字符串中的分组名称现在只能包含 ASCII 字母、数字和下划线。 (由 Serhiy Storchaka 在 gh-91760 [https://github.com/python/cpython/issues/91760] 中贡献。)
移除了自 Python 3.10 起已被弃用的
randrange()
功能。 以前,randrange(10.0)
会无损地转换为randrange(10)
。 现在,它将引发TypeError
。 此外,对于非整数值如randrange(10.5)
或randrange('10')
所引发的异常已从ValueError
改为TypeError
。 这也防止了randrange(1e25)
会从比randrange(10**25)
更大的范围中静默选择的问题。 (最初由 Serhiy Storchaka 在 gh-86388 [https://github.com/python/cpython/issues/86388] 中提议。)argparse.ArgumentParser
将从文件(例如fromfile_prefix_chars
选项)读取参数的编码格式和错误处理器从默认的文本编码格式(例如locale.getpreferredencoding(False)
调用)改为 filesystem encoding and error handler。 在 Windows 系统中参数文件应使用 UTF-8 而不是 ANSI 代码页来编码。移除了在 Python 3.4.7 和 3.5.4 中已被弃用的基于
asyncore
的smtpd
模块。 推荐的替代是基于asyncio
的 aiosmtpd [https://pypi.org/project/aiosmtpd/] PyPI 模块。shlex.split()
: 传入None
作为 s 参数现在将引发异常,而不是读取sys.stdin
。 该特性在 Python 3.9 中已被弃用。 (由 Victor Stinner 在 gh-94352 [https://github.com/python/cpython/issues/94352] 中贡献。)os
模块不再接受类似字节串的路径,如bytearray
和memoryview
类型:只接受明确的bytes
类型字节串。 (由 Victor Stinner 在 gh-98393 [https://github.com/python/cpython/issues/98393] 中贡献。)现在
syslog.openlog()
和syslog.closelog()
如果在子解释器中使用将失败。syslog.syslog()
仍可在子解释器中使用,但前提是syslog.openlog()
已在主解释器中被调用。 这些新限制不适用于主解释器,因此只有少数用户可能会受到影响。 这一改变有助于实现解释器隔离。 此外,syslog
是一个针对进程全局资源的包装器,而这些资源最好是由主解释器来管理。 (由 Donghee Na 在 gh-99127 [https://github.com/python/cpython/issues/99127] 中贡献。)未写入文档的
cached_property()
的锁定行为已被移除,因为该行为会在类的所有实例中锁定,从而导致高锁定争用。 这意味着如果两个线程同时运行,缓存属性获取函数现在可以在单个实例中运行不止一次。 对于大多数简单的缓存属性(例如那些幂等的并且只需根据实例的其他属性计算一个值的属性)来说这是没有问题的。 如果需要同步,可在缓存属性获取函数中或多线程访问点周围实现锁定操作。现在
sys._current_exceptions()
将返回从线程 ID 到异常实例的映射,而不是到(typ, exc, tb)
元组的映射。 (由 Irit Katriel 在 gh-103176 [https://github.com/python/cpython/issues/103176] 中贡献。)当使用
tarfile
或shutil.unpack_archive()
提取 tar 文件时,请传入 filter 参数来限制可能令人感到意外或危险的特性。 请参阅 解压缩过滤器 了解详情。由于在 PEP 701 [https://peps.python.org/pep-0701/] 中引入的更改
tokenize.tokenize()
和tokenize.generate_tokens()
函数的输出现在发生了改变。 这意味着不再为 f-字符输出STRING
词元而是改为产生 PEP 701 [https://peps.python.org/pep-0701/] 中描述的词元:除了用于对表达式组件进行分词的适当词元外现在还有FSTRING_START
,FSTRING_MIDDLE
和FSTRING_END
会被用于 f-字符串的“字符串”部分。 例如对于 f-字符串f"start {1+1} end"
旧版本的分词器会生成:
- 1,0-1,18: STRING 'f"start {1+1} end"'
而新版本将生成:
- 1,0-1,2: FSTRING_START 'f"'
- 1,2-1,8: FSTRING_MIDDLE 'start '
- 1,8-1,9: OP '{'
- 1,9-1,10: NUMBER '1'
- 1,10-1,11: OP '+'
- 1,11-1,12: NUMBER '1'
- 1,12-1,13: OP '}'
- 1,13-1,17: FSTRING_MIDDLE ' end'
- 1,17-1,18: FSTRING_END '"'
此外,支持 PEP 701 [https://peps.python.org/pep-0701/] 所需的改变还可能会导致一些细微的行为改变。 这些变化包括:
在对一些无效 Python 字符如
!
进行分词时相应词元的type
属性已从ERRORTOKEN
变为OP
。不完整的单行字符串现在也会像不完整的多行字符串一样引发
tokenize.TokenError
。某些不完整或无效的 Python 代码现在会引发
tokenize.TokenError
而不是在执行分词时返回任意的ERRORTOKEN
词元。在同一文件中混合使用制表符和空格作为缩进不再受到支持而是会引发
TabError
。
- 现在
threading
模块会预期_thread
模块具有_is_main_interpreter
属性。 它是一个不带参数的函数并会在当前解释器为主解释器时返回True
。
任何提供了自定义 _thread
模块的库或应用程序都应当提供 _is_main_interpreter()
。 (参见 gh-112826 [https://github.com/python/cpython/issues/112826]。)
构建变化
Python 不再使用
setup.py
来构建共享的 C 扩展模块。 头文件和库等编译参数在configure
脚本中检测。 扩展将由Makefile
来构建。 大多数扩展使用pkg-config
并回退为手动检测。 (由 Christian Heimes 在 gh-93939 [https://github.com/python/cpython/issues/93939] 中贡献。)现在需要用带有两个形参的
va_start()
,如va_start(args, format),
来构建 Python。 现在将不会再调用单个形参的va_start()
。 (由 Kumar Aditya 在 gh-93207 [https://github.com/python/cpython/issues/93207] 中贡献。)现在如果 Clang 编译器接受 ThinLTO 选项则 CPython 会将其作为默认的链接时间优化策略。 (由 Donghee Na 在 gh-89536 [https://github.com/python/cpython/issues/89536] 中贡献。)
在
Makefile
中添加了COMPILEALL_OPTS
变量以覆盖make install
中的compileall
选项 (默认值:-j0
)。 并将 3 条compileall
命令合并为单条命令以便一次性构建所有优化级别 (0, 1, 2) 的 .pyc 文件。 (由 Victor Stinner 在 gh-99289 [https://github.com/python/cpython/issues/99289] 中贡献。)为 64 位 LoongArch 添加了平台三选项:
loongarch64-linux-gnusf
loongarch64-linux-gnuf32
loongarch64-linux-gnu
(由 Zhang Na 在 gh-90656 [https://github.com/python/cpython/issues/90656] 中贡献。).)
PYTHON_FOR_REGEN
现在需要 Python 3.10 或更新版本。现在需要有 autoconf 2.71 和 aclocal 1.16.4 才能重新生成
!configure
。 (由 Christian Heimes 在 gh-89886 [https://github.com/python/cpython/issues/89886] 中贡献。)来自 python.org 的 Windows 版本和 macOS 安装程序现在使用 OpenSSL 3.0。
C API 的变化
新的特性
- PEP 697 [https://peps.python.org/pep-0697/]: 引入了 不稳定 C API 层,用于调试器和 JIT 编译器等低层级工具。 该 API 可能会在 CPython 的每个次要版本中发生变化而但发出弃用警告。 其内容在名称中以
PyUnstable_
前缀标记。
代码对象构造器:
PyUnstable_Code_New()
(由PyCode_New
改名而来)PyUnstable_Code_NewWithPosOnlyArgs()
(由PyCode_NewWithPosOnlyArgs
改名而来)
代码对象的额外存储 ( PEP 523 [https://peps.python.org/pep-0523/]):
PyUnstable_Eval_RequestCodeExtraIndex()
(由PyEvalRequestCodeExtraIndex
改名而来)PyUnstable_Code_GetExtra()
(由PyCodeGetExtra
改名而来)PyUnstable_Code_SetExtra()
(由PyCodeSetExtra
改名而来)
原有名称将继续可用直到对应的 API 发生改变。
(由 Petr Viktorin 在 gh-101101 [https://github.com/python/cpython/issues/101101] 中贡献。)
PEP 697 [https://peps.python.org/pep-0697/]: 添加了用于扩展实例内存布局不透明的类型的 API:
PyType_Spec.basicsize
可以为零或负数,用于以指定继承或扩展基类的大小。增加了
PyObject_GetTypeData()
和PyType_GetTypeDataSize()
以允许访问特定子类的实例数据。添加了
Py_TPFLAGS_ITEMS_AT_END
和PyObject_GetItemData()
以允许安全地扩展某些可变大小的类型,包括PyType_Type
。添加了
Py_RELATIVE_OFFSET
以允许用特定于子类的结构体来定义成员
。
(由 Petr Viktorin 在 gh-103509 [https://github.com/python/cpython/issues/103509] 中贡献。)
添加了新的 受限 C API 函数
PyType_FromMetaclass()
,它使用了额外的 metaclass 参数对现有的PyType_FromModuleAndSpec()
进行了泛化。 (由 Wenzel Jakob 在 gh-93012 [https://github.com/python/cpython/issues/93012] 中贡献。)在 受限 中添加了用于创建可使用 vectorcall 协议 来调用的对象的 API:
现在当一个类的 __call__()
方法被重新赋值时,该类的 Py_TPFLAGS_HAVE_VECTORCALL
旗标将被移除。 这使得 vectorcall 可以安全地用于可变类型(即没有不可变旗标 Py_TPFLAGS_IMMUTABLETYPE
的堆类型)。 未重载 tp_call
的可变类型现在继承了 Py_TPFLAGS_HAVE_VECTORCALL
旗标。 (由 Petr Viktorin 在 gh-93274 [https://github.com/python/cpython/issues/93274] 中贡献。)
新增了 Py_TPFLAGS_MANAGED_DICT
和 Py_TPFLAGS_MANAGED_WEAKREF
旗标。 这将允许扩展类以更少的记录消耗来支持对象 __dict__
和弱引用,占用更少内存并加快访问速度。
在 受限 API 中添加了使用 vectorcall 协议 执行调用的 API:
这意味着 vectorcall 调用协议的传入端和传出端现在都可以在 受限 API 中使用。 (由 Wenzel Jakob 在 gh-98586 [https://github.com/python/cpython/issues/98586] 中贡献。)
添加了两个新的公共函数
PyEval_SetProfileAllThreads()
和PyEval_SetTraceAllThreads()
,允许在调用的同时在所有运行线程中设置追踪和性能分析函数。 (由 Pablo Galindo 在 gh-93503 [https://github.com/python/cpython/issues/93503] 中贡献。)为 C API 添加了新函数
PyFunction_SetVectorcall()
用于设置给定PyFunctionObject
的 vectorcall 字段。 (由 Andrew Frost 在 gh-92257 [https://github.com/python/cpython/issues/92257] 中贡献。)C API 现在允许通过
PyDict_AddWatcher()
、PyDict_Watch()
和相关 API 注册回调,以便在字典被修改时调用。 这主要用于优化解释器、JIT 编译器或调试器。 (由 Carl Meyer 在 gh-91052 [https://github.com/python/cpython/issues/91052] 中贡献。)添加了
PyType_AddWatcher()
和PyType_Watch()
API 用于注册回调以接收类型变更通知。 (由 Carl Meyer 在 gh-91051 [https://github.com/python/cpython/issues/91051] 中贡献。)添加了
PyCode_AddWatcher()
和PyCode_ClearWatcher()
API 用于注册回调以接收代码对象创建和销毁时的通知。 (由 Itamar Oren 在 gh-91054 [https://github.com/python/cpython/issues/91054] 中贡献。)添加了
PyFrame_GetVar()
和PyFrame_GetVarString()
函数用于通过名称来获取帧变量。 (由 Victor Stinner 在 gh-91248 [https://github.com/python/cpython/issues/91248] 中贡献。)添加
PyErr_GetRaisedException()
和PyErr_SetRaisedException()
用于保存和恢复当前异常。 这些函数返回并接受单个异常对象,而不是像现在已弃用的PyErr_Fetch()
和PyErr_Restore()
那样的三个参数。 这样不容易出错并且更为高效。 (由 Mark Shannon 在 gh-101578 [https://github.com/python/cpython/issues/101578] 中贡献。)添加了
PyErrChainExceptions1
,它接受一个异常实例,用于取代旧式 APIPyErrChainExceptions
,后者现已被弃用。 (由 Mark Shannon 在 gh-101578 [https://github.com/python/cpython/issues/101578] 中贡献。)添加了
PyException_GetArgs()
和PyException_SetArgs()
作为便捷函数用于检索和修改传递给异常的构造函数的args
。 (由 Mark Shannon 在 gh-101578 [https://github.com/python/cpython/issues/101578] 中贡献。)添加了
PyErr_DisplayException()
,它接受一个异常实例,用于取代旧式 APIPyErr_Display()
。 (由 Irit Katriel 在 gh-102755 [https://github.com/python/cpython/issues/102755] 中贡献。)
PEP 683 [https://peps.python.org/pep-0683/]: 引入了 永生对象,它允许对象绕过引用计数,并对 C-API 进行相应修改:
PyIMMORTAL_REFCNT
: 定义对象的引用计数- 为永生对象。
PyIsImmortal
检测一个对象是否具有永生引用计数。PyObject_HEAD_INIT
这将把引用计数初始化为PyIMMORTAL_REFCNT
当配合Py_BUILD_CORE
使用时。
SSTATE_INTERNED_IMMORTAL
一个针对内部 unicode 对象的标识符- 为永生对象。
SSTATE_INTERNED_IMMORTAL_STATIC
一个针对内部 unicode- 为永生且静态的对象
sys.getunicodeinternedsize
这将返回总计的 unicode- 被管理的对象。现在
refleak.py
需要这样才能正确地追踪引用计数和分配的块
(由 Eddie Elizondo 在 gh-84436 [https://github.com/python/cpython/issues/84436] 中贡献。)
PEP 684 [https://peps.python.org/pep-0684/]: 新增了
Py_NewInterpreterFromConfig()
函数和PyInterpreterConfig
,可用于创建具有单独 GIL 的子解释器。 (更多信息参见 PEP 684: 每解释器 GIL。) (由 Eric Snow 在 gh-104110 [https://github.com/python/cpython/issues/104110] 中贡献。)在 3.12 版的受限 C API 中,
Py_INCREF()
和Py_DECREF()
函数现在使用不透明函数调用的方式实现以隐藏实现细节。 (由 Victor Stinner 在 gh-105387 [https://github.com/python/cpython/issues/105387] 中贡献。)
移植到 Python 3.12
基于
Py_UNICODE*
表示形式的旧式 Unicode API 已被移除。 请迁移到基于 UTF-8 或wchar_t*
的 API。PyArg_ParseTuple()
等参数解析函数不再支持基于Py_UNICODE*
的格式(例如u
,Z
等)。 请迁移到其他 Unicode 格式如s
,z
,es
和U
。tp_weaklist
对于所有静态内置类型将始终为NULL
。 这是PyTypeObject
上的一个内部专属字段,但我们还是要指出这一变化以防有人碰巧仍然直接访问到该字段。 为避免出现中断,请考虑改用现有的公共 C-API,或在必要时使用(仅限内部使用的)宏PyObjectGET_WEAKREFS_LISTPTR()
。现在这个内部专用的
PyTypeObject.tp_subclasses
可能不是一个有效的对象指针。 为了反映这一点我们将其类型改为 void*。 我们提到这一点是为了防止有人碰巧直接访问到这个内部专用字段。
要获取子类的列表,可调用 Python 方法 __subclasses__()
(例如使用 PyObject_CallMethod()
)。
在
PyUnicode_FromFormat()
和PyUnicode_FromFormatV()
中添加对更多格式选项(左对齐、八进制、大写十六进制、intmax_t
、ptrdiff_t
、wchar_t
C 字符串、可变宽度和精度)的支持。 (由 Serhiy Storchaka 在 gh-98836 [https://github.com/python/cpython/issues/98836] 中贡献。)PyUnicode_FromFormat()
和PyUnicode_FromFormatV()
中未被识别的格式字符现在会设置一个SystemError
。 在之前的版本中它会导致格式字符串的所有其他部分被原样复制到结果字符串中,并丢弃任何额外的参数。 (由 Serhiy Storchaka 在 gh-95781 [https://github.com/python/cpython/issues/95781] 中贡献。)修复了
PyUnicode_FromFormat()
和PyUnicode_FromFormatV()
中错误的标志位置。 (由 Philip Georgi 在 gh-95504 [https://github.com/python/cpython/issues/95504] 中贡献。)想要添加
__dict__
或弱引用槽位的扩展类应当分别使用Py_TPFLAGS_MANAGED_DICT
和Py_TPFLAGS_MANAGED_WEAKREF
来代替tp_dictoffset
和tp_weaklistoffset
。tp_dictoffset
和tp_weaklistoffset
的使用仍然受到支持,但并不完全支持多重继承 (gh-95589 [https://github.com/python/cpython/issues/95589]),而且性能可能会变差。 声明了Py_TPFLAGS_MANAGED_DICT
的类必须调用PyObjectVisitManagedDict()
和PyObjectClearManagedDict()
来遍历并清空其实例的字典。 要清空弱引用,请像之前一样调用PyObject_ClearWeakRefs()
。PyUnicode_FSDecoder()
函数不再接受类似字节串的路径,如bytearray
和memoryview
类型:只接受明确的bytes
类型字节字符串。 (由 Victor Stinner 在 gh-98393 [https://github.com/python/cpython/issues/98393] 中贡献。)Py_CLEAR
、Py_SETREF
和Py_XSETREF
宏现在只会对其参数求值一次。如果参数有附带影响,这些附带影响将不会再重复。 (由 Victor Stinner 在 gh-98724 [https://github.com/python/cpython/issues/98724] 中贡献。)解释器的错误指示器现在总是规范化的。 这意味着
PyErr_SetObject()
、PyErr_SetString()
以及其他设置错误指示器的函数在保存异常之前都会将其规范化。 (由 Mark Shannon 在 gh-101578 [https://github.com/python/cpython/issues/101578] 中贡献。)PyRefTotal
已不再具有重要性而保留它只是为了 ABI 的兼容性。 请注意,这是一个内部全局变量并且仅在调试版本中可用。 如果你碰巧要使用它那么你需要开始使用PyGetGlobalRefTotal()
。下面的函数将为新创建的类型选择一个合适的元类:
创建具有重载了 tp_new
的元类的类的做法已被弃用,在 Python 3.14+ 中将被禁止。 请注意这些函数会忽略元类的 tp_new
,从而可能导致不完整的初始化。
请注意 PyType_FromMetaclass()
(在 Python 3.12 中新增) 已禁止创建具有重载了 tp_new
(在 Python 中为 __new__()
) 的元类的类。
由于 tp_new
重载了PyType_From*
函数的几乎所有内容,因此两者互不兼容。 现有的行为 — 在创建类型的一些步骤中忽略元类 — 通常都是不安全的,因为(元)类会假定 tp_new
已被调用。 目前还没有简单通用的绕过方式。 以下办法之一可能对你有用:
如果你控制着元类,请避免在其中使用
tp_new
:如初始化可被跳过,则可以改在
tp_init
中完成。如果元类不需要从 Python 执行实例化,则使用
Py_TPFLAGS_DISALLOW_INSTANTIATION
旗标将其tp_new
设为NULL
。 这将使其可被PyType_From*
函数接受。
避免使用
PyType_From*
函数:如果不需要 C 专属的特性(槽位或设置实例大小),请通过 调用 元类来创建类型。如果你 知道 可以安全地跳过
tp_new
,就使用 Python 中的warnings.catch_warnings()
过滤掉弃用警告。
PyOS_InputHook
和PyOS_ReadlineFunctionPointer
将不再在 子解释器 中被调用。 这是因为客户端通常依赖进程级的全局状态(而这些回调没有办法恢复扩展模块状态)。
这也避免了扩展程序在不支持(或尚未被加载)的子解释器中运行的情况。 请参阅 gh-104668 [https://github.com/python/cpython/issues/104668] 了解更多信息。
PyLongObject
对其内部字段进行了修改以提高性能。 虽然PyLongObject
的内部字段是私有的,但某些扩展模块会使用它们。 内部字段不应再被直接访问,而应改用以PyLong_…
打头的 API 函数。 新增了两个 暂定 API 函数用于高效访问适配至单个机器字的PyLongObject
的值:通过
PyMem_SetAllocator()
设置的自定义分配器现在必须是线程安全的,无论内存域是什么。 没有自己的状态的分配器,包括“钩子”将不会受影响。 如果你的自定义分配器还不是线程安全的且你需要指导则请创建一个新的 GitHub 问题并抄送给@ericsnowcurrently
。
弃用
根据 PEP 699 [https://peps.python.org/pep-0699/] 的要求,
PyDictObject
中的ma_version_tag
字段对于扩展模块已被弃用。 访问该字段将在编译时生成编译器警告。 该字段将在 Python 3.14 中移除。 (由 Ramvikrams 和 Kumar Aditya 在 gh-101193 [https://github.com/python/cpython/issues/101193] 中贡献。 PEP 由 Ken Jin 撰写。)已弃用的全局配置变量:
Py_HashRandomizationFlag
: 使用PyConfig.use_hash_seed
和PyConfig.hash_seed
Py_LegacyWindowsFSEncodingFlag
: 使用PyPreConfig.legacy_windows_fs_encoding
Py_FileSystemDefaultEncoding
: 使用PyConfig.filesystem_encoding
Py_HasFileSystemDefaultEncoding
: 使用PyConfig.filesystem_encoding
Py_FileSystemDefaultEncodeErrors
: 使用PyConfig.filesystem_errors
Py_UTF8Mode
: 使用PyPreConfig.utf8_mode
(参见Py_PreInitialize()
)
Py_InitializeFromConfig()
API 应当改为使用 PyConfig
。 (由 Victor Stinner 在 gh-77782 [https://github.com/python/cpython/issues/77782] 中贡献。)
使用可变的基类创建
不可变类型
的做法已被弃用并将在 Python 3.14 中被禁用。 (gh-95388 [https://github.com/python/cpython/issues/95388])structmember.h
头文件已被弃用,不过它仍可继续使用也没有计划将其移除。
现在只需包括 Python.h
即可获得其内容,如果找不到请添加 Py
前缀:
类型宏如
Py_T_INT
,Py_T_DOUBLE
等(之前为T_INT
,T_DOUBLE
等)旗标
Py_READONLY
(之前为READONLY
) 和Py_AUDIT_READ
(之前为全大写形式)
Python.h
上有几个项目没有暴露:
T_OBJECT
(使用Py_T_OBJECT_EX
)T_NONE
(之前未写入文档,并且相当怪异)不进行任何操作的宏
WRITE_RESTRICTED
。RESTRICTED
和READ_RESTRICTED
宏,等同于Py_AUDIT_READ
。在某些配置中,
Python.h
未包含
。使用offsetof()
时,应手动将其包含在内。
已被弃用的头文件将继续以原来的名称提供原来的内容。 你的旧代码可以保持不变,除非额外的包括指令和无命名空间宏会给你带来很大困扰。
(由 Petr Viktorin 在 gh-47146 [https://github.com/python/cpython/issues/47146] 中贡献,基于 Alexander Belopolsky 和 Matthias Braun 在先前的工作。).)
PyErr_Fetch()
和PyErr_Restore()
已被弃用。请使用PyErr_GetRaisedException()
和PyErr_SetRaisedException()
代替。(由 Mark Shannon 在:gh:101578 贡献)。PyErr_Display()
已被弃用,请改用PyErr_DisplayException()
。 (由 Irit Katriel 在 gh-102755 [https://github.com/python/cpython/issues/102755] 中贡献。)PyErrChainExceptions
已被弃用。 请改用PyErrChainExceptions1
。 (由 Irit Katriel 在 gh-102192 [https://github.com/python/cpython/issues/102192] 中贡献。)使用
PyType_FromSpec()
,PyType_FromSpecWithBases()
或PyType_FromModuleAndSpec()
来创建所属元类重载了tp_new
的类的做法已被弃用。 请改为调用相应元类。is deprecated. Call the metaclass instead.
计划在 Python 3.14 中移除
PyDictObject
中的ma_version_tag
字段用于扩展模块 ( PEP 699 [https://peps.python.org/pep-0699/] ; gh-101193 [https://github.com/python/cpython/issues/101193] )。创建
immutable types
的可变基础 ( gh-95388 [https://github.com/python/cpython/issues/95388] )。用于配置 Python 的初始化的函数,在 Python 3.11 中已弃用:
PySys_SetArgvEx()
: 改为设置PyConfig.argv
。PySys_SetArgv()
: 改为设置PyConfig.argv
。Py_SetProgramName()
: 改为设置PyConfig.program_name
。Py_SetPythonHome()
: 改为设置PyConfig.home
。
Py_InitializeFromConfig()
API 应与 PyConfig
一起使用。
全局配置变量:
Py_HashRandomizationFlag
: 改用PyConfig.use_hash_seed
和PyConfig.hash_seed
。Py_LegacyWindowsFSEncodingFlag
: 改用PyPreConfig.legacy_windows_fs_encoding
。Py_LegacyWindowsStdioFlag
: 改用PyConfig.legacy_windows_stdio
。Py_FileSystemDefaultEncoding
: 改用PyConfig.filesystem_encoding
。Py_HasFileSystemDefaultEncoding
: 改用PyConfig.filesystem_encoding
。Py_FileSystemDefaultEncodeErrors
: 改用PyConfig.filesystem_errors
。Py_UTF8Mode
: 改用PyPreConfig.utf8_mode
。 (参见Py_PreInitialize()
)
Py_InitializeFromConfig()
API 应与 PyConfig
一起使用。
Python 3.15 中的待移除功能
捆绑的
libmpdecimal
副本。The
PyImport_ImportModuleNoBlock()
: 改用PyImport_ImportModule()
。PyWeakref_GetObject()
和PyWeakref_GET_OBJECT()
: 改用PyWeakref_GetRef()
。Py_UNICODE
类型和Py_UNICODE_WIDE
宏:改用wchar_t
。Python 初始化函数
PySys_ResetWarnOptions()
: 改为清除sys.warnoptions
和warnings.filters
。Py_GetExecPrefix()
: 改为获取sys.base_exec_prefix
和sys.exec_prefix
。Py_GetPath()
: 改为获取sys.path
。Py_GetPrefix()
: 改为获取sys.base_prefix
和sys.prefix
。Py_GetPythonHome()
: 改为获取PyConfig.home
或PYTHONHOME
环境变量。
计划在未来版本中移除
以下 API 已被弃用,将被移除,但目前尚未确定移除日期。
Py_TPFLAGS_HAVE_FINALIZE
: 自 Python 3.8 起不再需要。PySlice_GetIndicesEx()
: 改用PySlice_Unpack()
andPySlice_AdjustIndices()
。PyUnicode_AsDecodedObject()
: 改用PyCodec_Decode()
。PyUnicode_AsDecodedUnicode()
: 改用PyCodec_Decode()
。PyUnicode_AsEncodedObject()
: 改用PyCodec_Encode()
。PyUnicode_AsEncodedUnicode()
: 改用PyCodec_Encode()
。PyUnicode_READY()
: 自 Python 3.12 起不再需要PyErr_Display()
: 改用PyErr_DisplayException()
。PyErrChainExceptions()
: 改用PyErrChainExceptions1()
。PyBytesObject.ob_shash
成员:改为调用PyObject_Hash()
。PyDictObject.ma_version_tag
成员。线程本地存储 (TLS) API:
移除
移除
token.h
头文件。从来就没有任何公开的 C 语言标记程序接口。token.h
头文件只是为 Python 内部使用而设计的。(由 Victor Stinner 在 gh-92651 [https://github.com/python/cpython/issues/92651] 提供)。旧式 Unicode API 已被移除。 请参阅 PEP 623 [https://peps.python.org/pep-0623/] 了解详情。for detail.
PyUnicode_WCHAR_KIND
PyUnicode_AS_UNICODE()
PyUnicode_AsUnicode()
PyUnicode_AsUnicodeAndSize()
PyUnicode_AS_DATA()
PyUnicode_FromUnicode()
PyUnicode_GET_SIZE()
PyUnicode_GetSize()
PyUnicode_GET_DATA_SIZE()
移除了
PyUnicode_InternImmortal()
函数宏。 (由 Victor Stinner 在 gh-85858 [https://github.com/python/cpython/issues/85858] 中贡献。).)