弃用¶
Pending Removal in Python 3.14¶
argparse
: The type, choices, and metavar parameters ofargparse.BooleanOptionalAction
are deprecated and will be removed in 3.14. (Contributed by Nikita Sobolev in gh-92248.)ast
: The following features have been deprecated in documentation since Python 3.8, now cause aDeprecationWarning
to be emitted at runtime when they are accessed or used, and will be removed in Python 3.14:ast.Num
ast.Str
ast.Bytes
ast.NameConstant
ast.Ellipsis
Use
ast.Constant
instead. (Contributed by Serhiy Storchaka in gh-90953.)-
The child watcher classes
MultiLoopChildWatcher
,FastChildWatcher
,AbstractChildWatcher
andSafeChildWatcher
are deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in gh-94597.)asyncio.set_child_watcher()
,asyncio.get_child_watcher()
,asyncio.AbstractEventLoopPolicy.set_child_watcher()
andasyncio.AbstractEventLoopPolicy.get_child_watcher()
are deprecated and will be removed in Python 3.14. (Contributed by Kumar Aditya in gh-94597.)The
get_event_loop()
method of the default event loop policy now emits aDeprecationWarning
if there is no current event loop set and it decides to create one. (Contributed by Serhiy Storchaka and Guido van Rossum in gh-100160.)
collections.abc
: DeprecatedByteString
. PreferSequence
orBuffer
. For use in typing, prefer a union, likebytes | bytearray
, orcollections.abc.Buffer
. (Contributed by Shantanu Jain in gh-91896.)email
: Deprecated the isdst parameter inemail.utils.localtime()
. (Contributed by Alan Williams in gh-72346.)importlib.abc
deprecated classes:importlib.abc.ResourceReader
importlib.abc.Traversable
importlib.abc.TraversableResources
Use
importlib.resources.abc
classes instead:(Contributed by Jason R. Coombs and Hugo van Kemenade in gh-93963.)
itertools
had undocumented, inefficient, historically buggy, and inconsistent support for copy, deepcopy, and pickle operations. This will be removed in 3.14 for a significant reduction in code volume and maintenance burden. (Contributed by Raymond Hettinger in gh-101588.)multiprocessing
: The default start method will change to a safer one on Linux, BSDs, and other non-macOS POSIX platforms where'fork'
is currently the default (gh-84559). Adding a runtime warning about this was deemed too disruptive as the majority of code is not expected to care. Use theget_context()
orset_start_method()
APIs to explicitly specify when your code requires'fork'
. See 上下文和启动方法.pathlib
:is_relative_to()
andrelative_to()
: passing additional arguments is deprecated.pkgutil
:find_loader()
andget_loader()
now raiseDeprecationWarning
; useimportlib.util.find_spec()
instead. (Contributed by Nikita Sobolev in gh-97850.)pty
:master_open()
: usepty.openpty()
.slave_open()
: usepty.openpty()
.
-
version
andversion_info
.execute()
andexecutemany()
if named placeholders are used and parameters is a sequence instead of adict
.
typing
:ByteString
, deprecated since Python 3.9, now causes aDeprecationWarning
to be emitted when it is used.urllib
:urllib.parse.Quoter
is deprecated: it was not intended to be a public API. (Contributed by Gregory P. Smith in gh-88168.)
Pending Removal in 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 起已被弃用。
-
过时且很少被使用的
CGIHTTPRequestHandler
自 Python 3.13 起已被弃用。 不存在直接的替代品。 对于建立带有请求处理器的 Web 服务程序来说 任何东西 都比 CGI 要好。用于 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()
自 Python 3.13 起已被弃用。 请使用os.path.isreserved()
来检测 Windows 上的保留路径。
-
java_ver()
自 Python 3.13 起已被弃用。 此函数仅对 Jython 支持有用,具有令人困惑的 API,并且大部分未经测试。
-
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 中贡献。)
-
The undocumented keyword argument syntax for creating
NamedTuple
classes (e.g.Point = NamedTuple("Point", x=int, y=int)
) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead.When using the functional syntax of
TypedDict
s, failing to pass a value to the fields parameter (TD = TypedDict("TD")
) or passingNone
(TD = TypedDict("TD", None)
) has been deprecated since Python 3.13. Useclass TD(TypedDict): pass
orTD = TypedDict("TD", {})
to create a TypedDict with zero field.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()
is deprecated and will be removed in Python 3.16, useinspect.iscoroutinefunction()
instead. (Contributed by Jiahao Li and Kumar Aditya in gh-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 起被弃用。
Pending Removal in Future Versions¶
以下API将会被移除,尽管具体时间还未确定。
argparse
: Nesting argument groups and nesting mutually exclusive groups are deprecated.-
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)对
__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 中贡献。)-
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 中贡献。)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
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()
。
unittest.IsolatedAsyncioTestCase
: 从测试用例返回不为None
的值的做法已被弃用。urllib.parse
函数已被弃用:改用urlparse()
splitattr()
splithost()
splitnport()
splitpasswd()
splitport()
splitquery()
splittag()
splittype()
splituser()
splitvalue()
to_bytes()
urllib.request
:URLopener
andFancyURLopener
style of invoking requests is deprecated. Use newerurlopen()
functions and methods.wsgiref
:SimpleHandler.stdout.write()
不应执行部分写入。xml.etree.ElementTree
: 对Element
的真值测试已被弃用。 在未来的发布版中它将始终返回True
。 建议改用显式的len(elem)
或elem is not None
测试。zipimport.zipimporter.load_module()
is deprecated: useexec_module()
instead.
C API Deprecations¶
Pending Removal in Python 3.14¶
The
ma_version_tag
field inPyDictObject
for extension modules (PEP 699; gh-101193).Creating
immutable types
with mutable bases (gh-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_DebugFlag
: UsePyConfig.parser_debug
instead.Py_VerboseFlag
: UsePyConfig.verbose
instead.Py_QuietFlag
: UsePyConfig.quiet
instead.Py_InteractiveFlag
: UsePyConfig.interactive
instead.Py_InspectFlag
: UsePyConfig.inspect
instead.Py_OptimizeFlag
: UsePyConfig.optimization_level
instead.Py_NoSiteFlag
: UsePyConfig.site_import
instead.Py_BytesWarningFlag
: UsePyConfig.bytes_warning
instead.Py_FrozenFlag
: UsePyConfig.pathconfig_warnings
instead.Py_IgnoreEnvironmentFlag
: UsePyConfig.use_environment
instead.Py_DontWriteBytecodeFlag
: UsePyConfig.write_bytecode
instead.Py_NoUserSiteDirectory
: UsePyConfig.user_site_directory
instead.Py_UnbufferedStdioFlag
: UsePyConfig.buffered_stdio
instead.Py_HashRandomizationFlag
: UsePyConfig.use_hash_seed
andPyConfig.hash_seed
instead.Py_IsolatedFlag
: UsePyConfig.isolated
instead.Py_LegacyWindowsFSEncodingFlag
: UsePyPreConfig.legacy_windows_fs_encoding
instead.Py_LegacyWindowsStdioFlag
: UsePyConfig.legacy_windows_stdio
instead.Py_FileSystemDefaultEncoding
: UsePyConfig.filesystem_encoding
instead.Py_HasFileSystemDefaultEncoding
: UsePyConfig.filesystem_encoding
instead.Py_FileSystemDefaultEncodeErrors
: UsePyConfig.filesystem_errors
instead.Py_UTF8Mode
: UsePyPreConfig.utf8_mode
instead. (seePy_PreInitialize()
)
Py_InitializeFromConfig()
API 应与PyConfig
一起使用。
Pending Removal in Python 3.15¶
捆绑的
libmpdecimal
副本。The
PyImport_ImportModuleNoBlock()
: 改用PyImport_ImportModule()
。PyWeakref_GetObject()
andPyWeakref_GET_OBJECT()
: UsePyWeakref_GetRef()
instead.Py_UNICODE
类型和Py_UNICODE_WIDE
宏:改用wchar_t
。Python initialization functions:
PySys_ResetWarnOptions()
: 改为清除sys.warnoptions
和warnings.filters
。Py_GetExecPrefix()
: Getsys.base_exec_prefix
andsys.exec_prefix
instead.Py_GetPath()
: Getsys.path
instead.Py_GetPrefix()
: Getsys.base_prefix
andsys.prefix
instead.Py_GetProgramFullPath()
: Getsys.executable
instead.Py_GetProgramName()
: Getsys.executable
instead.Py_GetPythonHome()
: GetPyConfig.home
or thePYTHONHOME
environment variable instead.
Pending Removal in Future Versions¶
以下 API 已被弃用,将被移除,但目前尚未确定移除日期。
Py_TPFLAGS_HAVE_FINALIZE
: 自 Python 3.8 起不再需要。PySlice_GetIndicesEx()
: 改用PySlice_Unpack()
andPySlice_AdjustIndices()
。PyUnicode_AsDecodedObject()
: 改用PyCodec_Decode()
。PyUnicode_AsDecodedUnicode()
: UsePyCodec_Decode()
instead.PyUnicode_AsEncodedObject()
: 改用PyCodec_Encode()
。PyUnicode_AsEncodedUnicode()
: UsePyCodec_Encode()
instead.PyUnicode_READY()
: 自 Python 3.12 起不再需要PyErr_Display()
: 改用PyErr_DisplayException()
。_PyErr_ChainExceptions()
: 改用_PyErr_ChainExceptions1()
。PyBytesObject.ob_shash
成员:改为调用PyObject_Hash()
。PyDictObject.ma_version_tag
member.线程本地存储 (TLS) API: