typing
移除了
typing.io
和typing.re
命令空间,它们自 Python 3.8 起已被弃用。 这些命名空间中的条目可从typing
模块直接导入。 (由 Sebastian Rittau 在 gh-92871 [https://github.com/python/cpython/issues/92871] 中贡献。)移除了创建
TypedDict
类型的关键字参数方法,它在 Python 3.11 中已被弃用。 (由 Tomas Roun 在 gh-104786 [https://github.com/python/cpython/issues/104786] 中贡献。)
unittest
移除了下列
unittest
函数,它们在 Python 3.11 中已被弃用:unittest.findTestCases()
unittest.makeSuite()
unittest.getTestCaseNames()
请改用 TestLoader
方法:
(由 Hugo van Kemenade 在 gh-104835 [https://github.com/python/cpython/issues/104835] 中贡献。)
- 移除了未经测试且未写入文档的
TestProgram.usageExit()
方法,它在 Python 3.11 中已被弃用。 (由 Hugo van Kemenade 在 gh-104992 [https://github.com/python/cpython/issues/104992] 中贡献。)
urllib
- 移除了
urllib.request.urlopen()
函数的 cafile, capath 和 cadefault 等形参,它们在 Python 3.6 中已弃用。 应改为向 context 形参传入一个SSLContext
实例。 可以使用ssl.SSLContext.load_cert_chain()
函数来加载指定的证书,或是让ssl.create_default_context()
来选择操作系统的受信任证书颁发机构 (CA) 证书。 (由 Victor Stinner 在 gh-105382 [https://github.com/python/cpython/issues/105382] 中贡献。)
webbrowser
移除了未经测试且未写入文档的
MacOSX
类,它在 Python 3.11 中已弃用。 请改用MacOSXOSAScript
类(在 Python 3.2 中引入)。 (由 Hugo van Kemenade 在 gh-104804 [https://github.com/python/cpython/issues/104804] 中贡献。)移除了已被弃用的
MacOSXOSAScript._name
属性。 请改用MacOSXOSAScript.name
属性。 (由 Nikita Sobolev 在 gh-105546 [https://github.com/python/cpython/issues/105546] 中贡献。)
新的弃用
-
- 弃用对函数的
__code__
属性的赋值,其中新代码对象的类型与函数的类型不匹配。 不同的类型有:普通函数、生成器、异步生成器和协程。 (由 Irit Katriel 在 gh-81137 [https://github.com/python/cpython/issues/81137] 中贡献。)
- 弃用对函数的
-
- 在运行时弃用
'u'
格式代码 (wchar_t
)。 此格式代码自 Python 3.3 起在文档中已被弃用,并将在 Python 3.16 中被移除。对于 Unicode 字符,请使用'w'
格式代码 (Py_UCS4
)。 (由 Hugo van Kemenade 在 gh-80480 [https://github.com/python/cpython/issues/80480] 中贡献。)
- 在运行时弃用
-
弃用了未写入文档的
SetPointerType()
函数,并将在 Python 3.15 中移除。 (由 Victor Stinner 在 gh-105733 [https://github.com/python/cpython/issues/105733] 中贡献。)软弃用
ARRAY()
函数并改用type * length
乘法运算。 (由 Victor Stinner 在 gh-105733 [https://github.com/python/cpython/issues/105733] 中贡献。)
-
- 弃用了非标准且未写入文档的
Decimal
格式说明符'N'
,它仅在decimal
模块的 C 实现中受到支持。 (由 Serhiy Storchaka 在 gh-89902 [https://github.com/python/cpython/issues/89902] 中贡献。)
- 弃用了非标准且未写入文档的
dis
:- 弃用了
HAVE_ARGUMENT
分隔符。 改为在hasarg
中的成员检测。 (由 Irit Katriel 在 gh-109319 [https://github.com/python/cpython/issues/109319] 中贡献。).)
- 弃用了
-
- 在
gettext
模块中,弃用非整数作为考虑复数形式的函数和方法的参数,即使没有找到翻译时也不可以。 (由 Serhiy Storchaka 在 gh-88434 [https://github.com/python/cpython/issues/88434] 中贡献。)
- 在
glob
:- 弃用未写入文档的
glob0()
和glob1()
函数。改为使用glob()
并传递一个指定根目录的 path-like object 到 root_dir 形参。 (由 Barney Gale 在 gh-117337 [https://github.com/python/cpython/issues/117337] 中贡献。)
- 弃用未写入文档的
-
弃用
CGIHTTPRequestHandler
类,将在 Python 3.15 中移除。 基于进程的 CGI HTTP 服务器已经过时很久了。 该代码已经过时,无人维护,而且很少使用。 它极有可能出现安全和功能方面的程序错误。 (由 Gregory P. Smith 在 gh-109096 [https://github.com/python/cpython/issues/109096] 中贡献。)弃用:program:python -m http.server 命令行接口的:option:!—cgi
标志位 ,将在Python 3.15 中移除。(由 Gregory P. Smith 在:gh:
109096 中提供)。
-
- 软弃用 传给
guess_type()
的文件路径参数,改用guess_file_type()
。 (由 Serhiy Storchaka 在 gh-66543 [https://github.com/python/cpython/issues/66543] 中贡献。).)
- 软弃用 传给
re
:-
- 弃用
PurePath.is_reserved()
,将在 Python 3.15 中移除。 请使用os.path.isreserved()
来检测 Windows 上的保留路径。 (由 Barney Gale 在 gh-88569 [https://github.com/python/cpython/issues/88569] 中贡献。).)
- 弃用
-
- 弃用了
java_ver()
,并将在 Python 3.15 中移除。 此函数仅对 Jython 支持有用,具有令人困惑的 API,并且大部分未经测试。 (由 Nikita Sobolev 在 gh-116349 [https://github.com/python/cpython/issues/116349] 中贡献。).)
- 弃用了
-
- 弃用未写入文档的
ispackage()
函数。 (由 Zackery Spytz 在 gh-64020 [https://github.com/python/cpython/issues/64020] 中贡献。)
- 弃用未写入文档的
-
弃用向
connect()
函数和Connection
构造器传入多个位置参数的做法。 其余的形参在 Python 3.15 中将成为仅限关键字形参。 (由 Erlend E. Aasland 在 gh-107948 [https://github.com/python/cpython/issues/107948] 中贡献。)Deprecate passing name, number of arguments, and the callable as keyword arguments for
Connection.create_function()
andConnection.create_aggregate()
These parameters will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in gh-108278 [https://github.com/python/cpython/issues/108278].)Deprecate passing the callback callable by keyword for the
set_authorizer()
,set_progress_handler()
, andset_trace_callback()
Connection
methods. The callback callables will become positional-only in Python 3.15. (Contributed by Erlend E. Aasland in gh-108278 [https://github.com/python/cpython/issues/108278].)
sys
:- 弃用
_enablelegacywindowsfsencoding()
函数,并将在 Python 3.16 中移除。 请改用PYTHONLEGACYWINDOWSFSENCODING
环境变量。 (由 Inada Naoki 在 gh-73427 [https://github.com/python/cpython/issues/73427] 中贡献。)
- 弃用
-
- 弃用了未写入文档也未被使用的
TarFile.tarfile
属性,并将在 Python 3.16 中移除。 (在 gh-115256 [https://github.com/python/cpython/issues/115256] 中贡献。)
- 弃用了未写入文档也未被使用的
-
- 已弃用
TracebackException.exc_type
属性。 请改用TracebackException.exc_type_str
。 (由 Irit Katriel 在 gh-112332 [https://github.com/python/cpython/issues/112332] 中贡献。)
- 已弃用
-
弃用了未写入文档的用于创建
NamedTuple
类的关键字参数语法 (例如Point = NamedTuple("Point", x=int, y=int)
),将在 Python 3.15 中移除。 请改用基于类的语法或函数式语法。 (由 Alex Waygood 在 gh-105566 [https://github.com/python/cpython/issues/105566] 中贡献。)Deprecate omitting the fields parameter when creating a
NamedTuple
ortyping.TypedDict
class, and deprecate passingNone
to the fields parameter of both types. Python 3.15 will require a valid sequence for the fields parameter. To create a NamedTuple class with zero fields, useclass NT(NamedTuple): pass
orNT = NamedTuple("NT", ())
. To create a TypedDict class with zero fields, useclass TD(TypedDict): pass
orTD = TypedDict("TD", {})
. (Contributed by Alex Waygood in gh-105566 [https://github.com/python/cpython/issues/105566] and gh-105570 [https://github.com/python/cpython/issues/105570].)Deprecate the
typing.no_type_check_decorator()
decorator function, to be removed in in Python 3.15. After eight years in thetyping
module, it has yet to be supported by any major type checker. (Contributed by Alex Waygood in gh-106309 [https://github.com/python/cpython/issues/106309].)Deprecate
typing.AnyStr
. In Python 3.16, it will be removed fromtyping.__all__
, and aDeprecationWarning
will be emitted at runtime when it is imported or accessed. It will be removed entirely in Python 3.18. Use the new type parameter syntax instead. (Contributed by Michael The in gh-107116 [https://github.com/python/cpython/issues/107116].)
wave
:- Deprecate the
getmark()
,setmark()
, andgetmarkers()
methods of theWave_read
andWave_write
classes, to be removed in Python 3.15. (Contributed by Victor Stinner in gh-105096 [https://github.com/python/cpython/issues/105096].)
- Deprecate the
计划在 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
测试。
CPython 字节码的变化
- The oparg of
YIELD_VALUE
is now1
if the yield is part of a yield-from or await, and0
otherwise. The oparg ofRESUME
was changed to add a bit indicating if the except-depth is 1, which is needed to optimize closing of generators. (Contributed by Irit Katriel in gh-111354 [https://github.com/python/cpython/issues/111354].)
C API 的变化
新的特性
增加 PyMonitoring C API 用于生成 PEP 669 [https://peps.python.org/pep-0669/] 监控事件:
(由 Irit Katriel 在 gh-111997 [https://github.com/python/cpython/issues/111997] 中贡献。)
增加了
PyMutex
,它是占用一个字节的轻量级互斥锁,以及新的PyMutex_Lock()
和PyMutex_Unlock()
函数。 如果操作需要阻塞则PyMutex_Lock()
将释放 (当前持有的) GIL。 (由 Sam Gross 在 gh-108724 [https://github.com/python/cpython/issues/108724] 中贡献。)增加了 PyTime C API 以提供对系统时钟的访问:
(由 Victor Stinner 和 Petr Viktorin 在 gh-110850 [https://github.com/python/cpython/issues/110850] 中贡献。)
Add the
PyDict_ContainsString()
function with the same behavior asPyDict_Contains()
, but key is specified as a const char UTF-8 encoded bytes string, rather than a PyObject. (Contributed by Victor Stinner in gh-108314 [https://github.com/python/cpython/issues/108314].)Add the
PyDict_GetItemRef()
andPyDict_GetItemStringRef()
functions, which behave similarly toPyDict_GetItemWithError()
, but return a strong reference instead of a borrowed reference. Moreover, these functions return-1
on error, removing the need to checkPyErr_Occurred()
. (Contributed by Victor Stinner in gh-106004 [https://github.com/python/cpython/issues/106004].)Add the
PyDict_SetDefaultRef()
function, which behaves similarly toPyDict_SetDefault()
, but returns a strong reference instead of a borrowed reference. This function returns-1
on error,0
on insertion, and1
if the key was already present in the dictionary. (Contributed by Sam Gross in gh-112066 [https://github.com/python/cpython/issues/112066].)Add the
PyDict_Pop()
andPyDict_PopString()
functions to remove a key from a dictionary and optionally return the removed value. This is similar todict.pop()
, though there is no default value, andKeyError
is not raised for missing keys. (Contributed by Stefan Behnel and Victor Stinner in gh-111262 [https://github.com/python/cpython/issues/111262].)Add the
PyMapping_GetOptionalItem()
andPyMapping_GetOptionalItemString()
functions as alternatives toPyObject_GetItem()
andPyMapping_GetItemString()
respectively. The new functions do not raiseKeyError
if the requested key is missing from the mapping. These variants are more convenient and faster if a missing key should not be treated as a failure. (Contributed by Serhiy Storchaka in gh-106307 [https://github.com/python/cpython/issues/106307].)Add the
PyObject_GetOptionalAttr()
andPyObject_GetOptionalAttrString()
functions as alternatives toPyObject_GetAttr()
andPyObject_GetAttrString()
respectively. The new functions do not raiseAttributeError
if the requested attribute is not found on the object. These variants are more convenient and faster if the missing attribute should not be treated as a failure. (Contributed by Serhiy Storchaka in gh-106521 [https://github.com/python/cpython/issues/106521].)Add the
PyErr_FormatUnraisable()
function as an extension toPyErr_WriteUnraisable()
that allows customizing the warning message. (Contributed by Serhiy Storchaka in gh-108082 [https://github.com/python/cpython/issues/108082].)Add new functions that return a strong reference instead of a borrowed reference for frame locals, globals, and builtins, as part of PEP 667:
(由 Mark Shannon 和 Tian Gao 在 gh-74929 [https://github.com/python/cpython/issues/74929] 中贡献。)
Add the
Py_GetConstant()
andPy_GetConstantBorrowed()
functions to get strong or borrowed references to constants. For example,Py_GetConstant(Py_CONSTANT_ZERO)
returns a strong reference to the constant zero. (Contributed by Victor Stinner in gh-115754 [https://github.com/python/cpython/issues/115754].)Add the
PyImport_AddModuleRef()
function as a replacement forPyImport_AddModule()
that returns a strong reference instead of a borrowed reference. (Contributed by Victor Stinner in gh-105922 [https://github.com/python/cpython/issues/105922].)Add the
Py_IsFinalizing()
function to check whether the main Python interpreter is shutting down. (Contributed by Victor Stinner in gh-108014 [https://github.com/python/cpython/issues/108014].)Add the
PyList_GetItemRef()
function as a replacement forPyList_GetItem()
that returns a strong reference instead of a borrowed reference. (Contributed by Sam Gross in gh-114329 [https://github.com/python/cpython/issues/114329].)Add the
PyList_Extend()
andPyList_Clear()
functions, mirroring the Pythonlist.extend()
andlist.clear()
methods. (Contributed by Victor Stinner in gh-111138 [https://github.com/python/cpython/issues/111138].)Add the
PyLong_AsInt()
function. It behaves similarly toPyLong_AsLong()
, but stores the result in a C int instead of a C long. (Contributed by Victor Stinner in gh-108014 [https://github.com/python/cpython/issues/108014].)Add the
PyLong_AsNativeBytes()
,PyLong_FromNativeBytes()
, andPyLong_FromUnsignedNativeBytes()
functions to simplify converting between native integer types and Pythonint
objects. (Contributed by Steve Dower in gh-111140 [https://github.com/python/cpython/issues/111140].)Add
PyModule_Add()
function, which is similar toPyModule_AddObjectRef()
andPyModule_AddObject()
, but always steals a reference to the value. (Contributed by Serhiy Storchaka in gh-86493 [https://github.com/python/cpython/issues/86493].)Add the
PyObject_GenericHash()
function that implements the default hashing function of a Python object. (Contributed by Serhiy Storchaka in gh-113024 [https://github.com/python/cpython/issues/113024].)Add the
Py_HashPointer()
function to hash a raw pointer. (Contributed by Victor Stinner in gh-111545 [https://github.com/python/cpython/issues/111545].)Add the
PyObject_VisitManagedDict()
andPyObject_ClearManagedDict()
functions. which must be called by the traverse and clear functions of a type using thePy_TPFLAGS_MANAGED_DICT
flag. The pythoncapi-compat project [https://github.com/python/pythoncapi-compat/] can be used to use these functions with Python 3.11 and 3.12. (Contributed by Victor Stinner in gh-107073 [https://github.com/python/cpython/issues/107073].)Add the
PyRefTracer_SetTracer()
andPyRefTracer_GetTracer()
functions, which enable tracking object creation and destruction in the same way that thetracemalloc
module does. (Contributed by Pablo Galindo in gh-93502 [https://github.com/python/cpython/issues/93502].)Add the
PySys_AuditTuple()
function as an alternative toPySys_Audit()
that takes event arguments as a Pythontuple
object. (Contributed by Victor Stinner in gh-85283 [https://github.com/python/cpython/issues/85283].)Add the
PyThreadState_GetUnchecked()
function as an alternative toPyThreadState_Get()
that doesn't kill the process with a fatal error if it isNULL
. The caller is responsible for checking if the result isNULL
. (Contributed by Victor Stinner in gh-108867 [https://github.com/python/cpython/issues/108867].)Add the
PyType_GetFullyQualifiedName()
function to get the type's fully qualified name. The module name is prepended iftype.__module__
is a string and is not equal to either'builtins'
or'__main__'
. (Contributed by Victor Stinner in gh-111696 [https://github.com/python/cpython/issues/111696].)Add the
PyType_GetModuleName()
function to get the type's module name. This is equivalent to getting thetype.__module__
attribute. (Contributed by Eric Snow and Victor Stinner in gh-111696 [https://github.com/python/cpython/issues/111696].)Add the
PyUnicode_EqualToUTF8AndSize()
andPyUnicode_EqualToUTF8()
functions to compare a Unicode object with a const char* UTF-8 encoded string and1
if they are equal or0
otherwise. These functions do not raise exceptions. (Contributed by Serhiy Storchaka in gh-110289 [https://github.com/python/cpython/issues/110289].)增加
PyWeakref_GetRef()
函数作为PyWeakref_GetObject()
的替代,它将返回一个 strong reference 或是在引用对象不再存活时返回NULL
。 (由 Victor Stinner 在 gh-105927 [https://github.com/python/cpython/issues/105927] 中贡献。)增加了静默地忽略错误的函数的已修正变体形式:
这些新函数将返回 -1
表示错误而返回标准的 1
表示真值以及 0
表示假值。
(由 Serhiy Storchaka 在 gh-108511 [https://github.com/python/cpython/issues/108511] 中贡献。)
被改变的 C API
The keywords parameter of
PyArg_ParseTupleAndKeywords()
andPyArg_VaParseTupleAndKeywords()
now has type char const in C and const char const in C++, instead of char. In C++, this makes these functions compatible with arguments of type const char const, const char, or char const without an explicit type cast. In C, the functions only support arguments of type char const. This can be overridden with thePY_CXX_CONST
macro. (Contributed by Serhiy Storchaka in gh-65210 [https://github.com/python/cpython/issues/65210].)PyArg_ParseTupleAndKeywords()
now supports non-ASCII keyword parameter names. (Contributed by Serhiy Storchaka in gh-110815 [https://github.com/python/cpython/issues/110815].)The
PyCode_GetFirstFree()
function is now unstable API and is now namedPyUnstable_Code_GetFirstFree()
. (Contributed by Bogdan Romanyuk in gh-115781 [https://github.com/python/cpython/issues/115781].)The
PyDict_GetItem()
,PyDict_GetItemString()
,PyMapping_HasKey()
,PyMapping_HasKeyString()
,PyObject_HasAttr()
,PyObject_HasAttrString()
, andPySys_GetObject()
functions, each of which clears all errors which occurred when calling them now reports these errors usingsys.unraisablehook()
. You may replace them with other functions as recommended in the documentation. (Contributed by Serhiy Storchaka in gh-106672 [https://github.com/python/cpython/issues/106672].)为
PyUnicode_FromFormat()
增加了%T
,%#T
,%N
和%#N
格式的支持:%T
: 获取一个对象类型的完整限定名称%#T
: 同上,但使用冒号作为分隔符%N
: 获取一个类型的完整限定名称%#N
: 同上,但使用冒号作为分隔符
请参阅 PEP 737 [https://peps.python.org/pep-0737/] 了解详情。 (由 Victor Stinner 在 gh-111696 [https://github.com/python/cpython/issues/111696] 中贡献。)
You no longer have to define the
PY_SSIZE_T_CLEAN
macro before includingPython.h
when using#
formats in format codes. APIs accepting the format codes always usePy_ssize_t
for#
formats. (Contributed by Inada Naoki in gh-104922 [https://github.com/python/cpython/issues/104922].)如果 Python 是使用 调试模式 或
附带断言
构建的,PyTuple_SET_ITEM()
和PyList_SET_ITEM()
现在将通过一个断言来检查 index 参数。 (由 Victor Stinner 在 gh-106168 [https://github.com/python/cpython/issues/106168] 中贡献。)
受限 C API 的改变
下列函数现在被包括在受限 C API 中:
(由 Victor Stinner 在 gh-85283 [https://github.com/python/cpython/issues/85283], gh-85283 [https://github.com/python/cpython/issues/85283] 和 gh-116936 [https://github.com/python/cpython/issues/116936] 中贡献。)
- 使用
--with-trace-refs
(跟踪引用) 构建的 Python 现在支持 受限 API。 (由 Victor Stinner 在 gh-108634 [https://github.com/python/cpython/issues/108634] 中贡献。)
被移除的 C API
Remove several functions, macros, variables, etc with names prefixed by
_Py
or_PY
(which are considered private). If your project is affected by one of these removals and you believe that the removed API should remain available, please open a new issue to request a public C API and addcc: @vstinner
to the issue to notify Victor Stinner. (Contributed by Victor Stinner in gh-106320 [https://github.com/python/cpython/issues/106320].)移除在 Python 3.0 中已弃用的旧缓冲区协议。 改用 缓冲协议。
PyObject_CheckReadBuffer()
: UsePyObject_CheckBuffer()
to test whether the object supports the buffer protocol. Note thatPyObject_CheckBuffer()
doesn't guarantee thatPyObject_GetBuffer()
will succeed. To test if the object is actually readable, see the next example ofPyObject_GetBuffer()
.PyObject_AsCharBuffer()
,PyObject_AsReadBuffer()
: 改用PyObject_GetBuffer()
和PyBuffer_Release()
:
- Py_buffer view;
- if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) < 0) { return NULL;
- }
- // Use `view.buf` and `view.len` to read from the buffer.
- // You may need to cast buf as `(const char*)view.buf`.
- PyBuffer_Release(&view);
PyObject_AsWriteBuffer()
: UsePyObject_GetBuffer()
andPyBuffer_Release()
instead:
- Py_buffer view;
- if (PyObject_GetBuffer(obj, &view, PyBUF_WRITABLE) < 0) { return NULL;
- }
- // Use `view.buf` and `view.len` to write to the buffer.
- PyBuffer_Release(&view);
(由 Inada Naoki 在 gh-85275 [https://github.com/python/cpython/issues/85275] 中贡献。)
- 删除了在 Python 3.9 中弃用的各种函数:
PyEval_CallObject()
,PyEval_CallObjectWithKeywords()
: 改用PyObject_CallNoArgs()
或PyObject_Call()
。
警告
In PyObject_Call()
, positional arguments must be a tuple
and must not be NULL
, and keyword arguments must be a dict
or NULL
, whereas the removed functions checked argument types and accepted NULL
positional and keyword arguments. To replace PyEval_CallObjectWithKeywords(func, NULL, kwargs)
with PyObject_Call()
, pass an empty tuple as positional arguments using PyTuple_New(0)
.
PyEval_CallFunction()
: 改用PyObject_CallFunction()
。PyEval_CallMethod()
: 改用PyObject_CallMethod()
。PyCFunction_Call()
: 改用PyObject_Call()
。
(Contributed by Victor Stinner in gh-105107 [https://github.com/python/cpython/issues/105107].)
- 移除了下列用于配置 Python 初始化的旧函数,它们在 Python 3.11 中已被弃用:
PySys_AddWarnOptionUnicode()
: 改用PyConfig.warnoptions
。PySys_AddWarnOption()
: UsePyConfig.warnoptions
instead.PySys_AddXOption()
: UsePyConfig.xoptions
instead.PySys_HasWarnOptions()
: UsePyConfig.xoptions
instead.PySys_SetPath()
: SetPyConfig.module_search_paths
instead.Py_SetPath()
: SetPyConfig.module_search_paths
instead.Py_SetStandardStreamEncoding()
: SetPyConfig.stdio_encoding
instead, and set also maybePyConfig.legacy_windows_stdio
(on Windows).PySetProgramFullPath()
: SetPyConfig.executable
instead.
Use the new PyConfig
API of the Python Initialization Configuration instead ( PEP 587 [https://peps.python.org/pep-0587/]), added to Python 3.8. (Contributed by Victor Stinner in gh-105145 [https://github.com/python/cpython/issues/105145].)
- Remove
PyEval_AcquireLock()
andPyEval_ReleaseLock()
functions, deprecated in Python 3.2. They didn't update the current thread state. They can be replaced with:
low-level
PyEval_AcquireThread()
andPyEval_RestoreThread()
;
(Contributed by Victor Stinner in gh-105182 [https://github.com/python/cpython/issues/105182].)
删除了在 Python 3.9 弃用的:c:func:!PyEval_ThreadsInitialized 函数。自Python 3.7 起,
Py_Initialize()
总是创建全局解释器锁 :调用:c:func:!PyEval_InitThreads 不做任何事情,而:c:func:!PyEval_ThreadsInitialized 总返回非零值。(由 Victor Stinner 在:gh:105182 中贡献。)Remove the
PyInterpreterStateGet()
alias toPyInterpreterState_Get()
which was kept for backward compatibility with Python 3.8. The pythoncapi-compat project [https://github.com/python/pythoncapi-compat/] can be used to getPyInterpreterState_Get()
on Python 3.8 and older. (Contributed by Victor Stinner in gh-106320 [https://github.com/python/cpython/issues/106320].)Remove the private
PyObjectFastCall()
function: usePyObject_Vectorcall()
which is available since Python 3.8 ( PEP 590 [https://peps.python.org/pep-0590/]). (Contributed by Victor Stinner in gh-106023 [https://github.com/python/cpython/issues/106023].)Remove the
cpython/pytime.h
header file, which only contained private functions. (Contributed by Victor Stinner in gh-106316 [https://github.com/python/cpython/issues/106316].)Remove the undocumented
PY_TIMEOUT_MAX
constant from the limited C API. (Contributed by Victor Stinner in gh-110014 [https://github.com/python/cpython/issues/110014].)Remove the old trashcan macros
Py_TRASHCAN_SAFE_BEGIN
andPy_TRASHCAN_SAFE_END
. Replace both with the new macrosPy_TRASHCAN_BEGIN
andPy_TRASHCAN_END
. (Contributed by Irit Katriel in gh-105111 [https://github.com/python/cpython/issues/105111].)
已弃用的 C API
已弃用旧的 Python 初始化函数:
PySys_ResetWarnOptions()
: 改为清除sys.warnoptions
和warnings.filters
。Py_GetPath()
: 改为获取sys.path
。Py_GetPrefix()
: 改为获取sys.prefix
。Py_GetPythonHome()
: 改为获取PyConfig.home
或PYTHONHOME
环境变量。
(由 Victor Stinner 在 gh-105145 [https://github.com/python/cpython/issues/105145] 中贡献。)
Soft deprecate the
PyEval_GetBuiltins()
,PyEval_GetGlobals()
, andPyEval_GetLocals()
functions, which return a borrowed reference. (Soft deprecated as part of PEP 667 [https://peps.python.org/pep-0667/].)Deprecate the
PyImport_ImportModuleNoBlock()
function, which is just an alias toPyImport_ImportModule()
since Python 3.3. (Contributed by Victor Stinner in gh-105396 [https://github.com/python/cpython/issues/105396].)Soft deprecate the
PyModule_AddObject()
function. It should be replaced withPyModule_Add()
orPyModule_AddObjectRef()
. (Contributed by Serhiy Storchaka in gh-86493 [https://github.com/python/cpython/issues/86493].)Deprecate the old
Py_UNICODE
andPY_UNICODE_TYPE
types and thePy_UNICODE_WIDE
define. Use thewchar_t
type directly instead. Since Python 3.3,Py_UNICODE
andPY_UNICODE_TYPE
are just aliases towchar_t
. (Contributed by Victor Stinner in gh-105156 [https://github.com/python/cpython/issues/105156].)Deprecate the
PyWeakref_GetObject()
andPyWeakref_GET_OBJECT()
functions, which return a borrowed reference. Replace them with the newPyWeakref_GetRef()
function, which returns a strong reference. The pythoncapi-compat project [https://github.com/python/pythoncapi-compat/] can be used to getPyWeakref_GetRef()
on Python 3.12 and older. (Contributed by Victor Stinner in gh-105927 [https://github.com/python/cpython/issues/105927].)
计划在 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:
构建变化
arm64-apple-ios
andarm64-apple-ios-simulator
are both now PEP 11 [https://peps.python.org/pep-0011/] tier 3 platforms. (PEP 730 written and implementation contributed by Russell Keith-Magee in gh-114099 [https://github.com/python/cpython/issues/114099].)aarch64-linux-android
andx86_64-linux-android
are both now PEP 11 [https://peps.python.org/pep-0011/] tier 3 platforms. (PEP 738 written and implementation contributed by Malcolm Smith in gh-116622 [https://github.com/python/cpython/issues/116622].)现在
wasm32-wasi
是 PEP 11 [https://peps.python.org/pep-0011/] 第 2 层级的平台。 (由 Brett Cannon 在 gh-115192 [https://github.com/python/cpython/issues/115192] 中贡献。)wasm32-emscripten
不再是 PEP 11 [https://peps.python.org/pep-0011/] 的受支持平台。 (由 Brett Cannon 在 gh-115192 [https://github.com/python/cpython/issues/115192] 中贡献。)现在构建 CPython 需要带有 C11 atomic 库支持的编译器、GCC 内置 atomic 函数或 MSVC 互锁内生函数。
Autoconf 2.71 and aclocal 1.16.5 are now required to regenerate the
configure
script. (Contributed by Christian Heimes in gh-89886 [https://github.com/python/cpython/issues/89886] and by Victor Stinner in gh-112090 [https://github.com/python/cpython/issues/112090].)需要 SQLite 3.15.2 或更新的版本才能构建
sqlite3
扩展模块。 (由 Erlend Aasland 在 gh-105875 [https://github.com/python/cpython/issues/105875] 中贡献。)CPython now bundles the mimalloc library [https://github.com/microsoft/mimalloc/] by default. It is licensed under the MIT license; see mimalloc license. The bundled mimalloc has custom changes, see gh-113141 [https://github.com/python/cpython/issues/113141] for details. (Contributed by Dino Viehland in gh-109914 [https://github.com/python/cpython/issues/109914].)
现在
configure
选项--with-system-libmpdec
默认为yes
。 捆绑的libmpdecimal
副本将在 Python 3.15 中被移除。使用
configure
--with-trace-refs
(跟踪引用) 构建的 Python 现在与 Python 发布构建版和 调试构建版 是 ABI 兼容的。 (由 Victor Stinner 在 gh-108634 [https://github.com/python/cpython/issues/108634] 中贡献。)On POSIX systems, the pkg-config (
.pc
) filenames now include the ABI flags. For example, the freethreaded build generatespython3.13t.pc
and the debug build generatespython3.13d.pc
.现在
errno
,fcntl
,grp
,md5
,pwd
,resource
,termios
,winsound
,ctypestest
,_multiprocessing.posixshmem
,_scproxy
,_stat
,_statistics
,_testconsole
,_testimportmultiple
和_uuid
C 扩展是使用 受限 C API 构建的。 (由 Victor Stinner 在 gh-85283 [https://github.com/python/cpython/issues/85283] 中贡献。)
Porting to Python 3.13
本节列出了先前描述的更改以及可能需要更改代码的其他错误修正.
Python API 的变化
PEP 667 引入了对
locals()
和f_locals
语义的多项更改:在 optimized scope 中调用
locals()
时,每次调用都会生成一个独立的快照,因此不再隐式更新之前返回的引用。要获得以往版本 CPython 的行为,现需显式调用以使用后来调用:func:!locals得到的结果来更新初次调用返回的字典。隐式使用 :func:!locals
的代码执行函数(如exec
和eval
)必须传入一个显式命名空间,才能在已优化的作用域中访问其结果。(此更改为 PEP 667 [https://peps.python.org/pep-0667/] 的一部分。)从模块作用域或类作用域的推导式中调用
locals
或(包括 ``exec
()eval
导致的间接调用)时,行为再次表现得像是推导式作为独立的嵌套函数运行(即不包含外部作用域的局部变量)。在 Python 3.12 中,此场景下的行为曾按照 PEP 709 [https://peps.python.org/pep-0709/] 更改为包含存放推导式的作用域的局部变量。(此更改为 PEP 667 [https://peps.python.org/pep-0667/] 的一部分。)在 optimized scope 中访问
FrameType.f_locals
现在会返回一个写入代理,而不是一个在不明确时间更新的快照。如果需要快照,必须使用dict
或该代理的.copy()
方法显式地创建。(此修改是 PEP 667 [https://peps.python.org/pep-0667/] 的一部分。)
当作为方法使用时,
functools.partial
现在会发出FutureWarning
。该行为将在 Python 的未来版本中更改。如果想保留旧行为,请将其包装在staticmethod()
中。(由 Serhiy Storchaka 在 gh-121027 [https://github.com/python/cpython/issues/121027] 贡献。)现在当无法获取到用户名时
getpass.getuser()
将会引发OSError
,而不是在非 Unix 平台上引发ImportError
或因密码数据库为空在 Unix 平台上引发KeyError
。gzip.GzipFile
的mode
属性值现在是字符串('rb'
或'wb'
)而不是整数(1
或2
)。zipfile.ZipFile.open()
返回的可读文件型对象的mode
属性值现在是'rb'
,而非'r'
。(由 Serhiy Storchaka 在 gh-115961 [https://github.com/python/cpython/issues/115961] 贡献。)mailbox.Maildir
现在会忽略以点(.
)开头的文件。(由 Zackery Spytz 在 gh-65559 [https://github.com/python/cpython/issues/65559] 贡献。)pathlib.Path.glob()
和rglob()
现在会在匹配模式以“**
”结尾时同时返回文件和目录,而不仅仅是目录。若要保持之前的行为,仅匹配目录,请添加尾部斜杠。threading
模块现在期望_thread
模块具有ismain_interpreter()
函数。该函数不接受任何参数,如果当前解释器是主解释器,则返回True
。
与模块的其他“私有”属性一样,任何提供自定义 _thread
模块的库或应用都必须提供 ismain_interpreter()
。(gh-112826 [https://github.com/python/cpython/issues/112826]。)
C API 的变化
Python.h
no longer includes the
standard header. It was included for thefinite()
function which is now provided by the
header. It should now be included explicitly if needed. Remove also theHAVE_IEEEFP_H
macro. (Contributed by Victor Stinner in gh-108765 [https://github.com/python/cpython/issues/108765].)Python.h
no longer includes these standard header files:
,
and
. If needed, they should now be included explicitly. For example,
provides theclock()
andgmtime()
functions,
provides theselect()
function, and
provides thefutimes()
,gettimeofday()
andsetitimer()
functions. (Contributed by Victor Stinner in gh-108765 [https://github.com/python/cpython/issues/108765].)On Windows,
Python.h
no longer includes the
standard header file. If needed, it should now be included explicitly. For example, it providesoffsetof()
function, andsize_t
andptrdiff_t
types. Including
explicitly was already needed by all other platforms, theHAVE_STDDEF_H
macro is only defined on Windows. (Contributed by Victor Stinner in gh-108765 [https://github.com/python/cpython/issues/108765].)If the
Py_LIMITED_API
macro is defined,Py_BUILD_CORE
,Py_BUILD_CORE_BUILTIN
andPy_BUILD_CORE_MODULE
macros are now undefined by
. (Contributed by Victor Stinner in gh-85283 [https://github.com/python/cpython/issues/85283].)The old trashcan macros
Py_TRASHCAN_SAFE_BEGIN
andPy_TRASHCAN_SAFE_END
were removed. They should be replaced by the new macrosPy_TRASHCAN_BEGIN
andPy_TRASHCAN_END
.
A tp_dealloc
function that has the old macros, such as:
- static void
- mytype_dealloc(mytype *p)
- {
- PyObject_GC_UnTrack(p);
- Py_TRASHCAN_SAFE_BEGIN(p);
- ...
- Py_TRASHCAN_SAFE_END
- }
应当按照以下方式迁移到新版宏:
- static void
- mytype_dealloc(mytype *p)
- {
- PyObject_GC_UnTrack(p);
- Py_TRASHCAN_BEGIN(p, mytype_dealloc)
- ...
- Py_TRASHCAN_END
- }
Note that Py_TRASHCAN_BEGIN
has a second argument which should be the deallocation function it is in. The new macros were added in Python 3.8 and the old macros were deprecated in Python 3.11. (Contributed by Irit Katriel in gh-105111 [https://github.com/python/cpython/issues/105111].)
PEP 667 introduces several changes to frame-related functions:
The effects of mutating the dictionary returned from
PyEval_GetLocals()
in an optimized scope have changed. New dict entries added this way will now only be visible to subsequentPyEval_GetLocals()
calls in that frame, asPyFrame_GetLocals()
,locals()
, andFrameType.f_locals
no longer access the same underlying cached dictionary. Changes made to entries for actual variable names and names added via the write-through proxy interfaces will be overwritten on subsequent calls toPyEval_GetLocals()
in that frame. The recommended code update depends on how the function was being used, so refer to the deprecation notice on the function for details.Calling
PyFrame_GetLocals()
in an optimized scope now returns a write-through proxy rather than a snapshot that gets updated at ill-specified times. If a snapshot is desired, it must be created explicitly (e.g. withPyDict_Copy()
), or by calling the newPyEval_GetFrameLocals()
API.PyFrame_FastToLocals()
andPyFrame_FastToLocalsWithError()
no longer have any effect. Calling these functions has been redundant since Python 3.11, whenPyFrame_GetLocals()
was first introduced.PyFrame_LocalsToFast()
no longer has any effect. Calling this function is redundant now thatPyFrame_GetLocals()
returns a write-through proxy for optimized scopes.
Python 3.13 removed many private functions. Some of them can be replaced using these alternatives:
PyDictPop()
:PyDict_Pop()
orPyDict_PopString()
;PyDictGetItemWithError()
:PyDict_GetItemRef()
;PyErrWriteUnraisableMsg()
:PyErr_FormatUnraisable()
;PyEvalSetTrace()
:PyEval_SetTrace()
orPyEval_SetTraceAllThreads()
;PyListExtend()
:PyList_Extend()
;PyLongAsInt()
:PyLong_AsInt()
;PyMemRawStrdup()
:strdup()
;PyMemStrdup()
:strdup()
;PyObjectClearManagedDict()
:PyObject_ClearManagedDict()
;PyObjectVisitManagedDict()
:PyObject_VisitManagedDict()
;PyThreadStateUncheckedGet()
:PyThreadState_GetUnchecked()
;PyTimeAsSecondsDouble()
:PyTime_AsSecondsDouble()
;PyTimeGetMonotonicClock()
:PyTime_Monotonic()
orPyTime_MonotonicRaw()
;PyTimeGetPerfCounter()
:PyTime_PerfCounter()
orPyTime_PerfCounterRaw()
;PyTimeGetSystemClock()
:PyTime_Time()
orPyTime_TimeRaw()
;PyTimeMAX
:PyTime_MAX
;PyTimeMIN
:PyTime_MIN
;PyTimet
:PyTime_t
;PyHashPointer()
:Py_HashPointer()
;PyIsFinalizing()
:Py_IsFinalizing()
.
The pythoncapi-compat project [https://github.com/python/pythoncapi-compat/] can be used to get most of these new functions on Python 3.12 and older.
回归测试的变化
- 现在使用
configure
--with-pydebug
编译的 Python 将支持-X presite=package.module
命令行选项。 如果被使用,它指明一个模块应当在解释器生命周期开始时,即site.py
被执行之前被导入。 (由 Łukasz Langa 在 gh-110769 [https://github.com/python/cpython/issues/110769] 中贡献。)
Notable changes in 3.13.1
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.