弃用¶
计划在 Python 3.14 中移除¶
argparse
:argparse.BooleanOptionalAction
的 type, choices 和 metavar 形参已被弃用并将在 3.14 中移除。 (由 Nikita Sobolev 在 gh-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 中贡献。)-
子监视器类
MultiLoopChildWatcher
,FastChildWatcher
,AbstractChildWatcher
和SafeChildWatcher
已被弃用并将在 Python 3.14 中移除。 (由 Kumar Aditya 在 gh-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 中贡献。)现在默认事件循环策略的
get_event_loop()
方法在当前事件循环未设置并决定创建一个时将发出DeprecationWarning
。 (由 Serhiy Storchaka 和 Guido van Rossum 在 gh-100160 中贡献。)
email
: 已弃用email.utils.localtime()
中的 isdst 形参。 (由 Alan Williams 在 gh-72346 中贡献。)importlib.abc
中已弃用的类:importlib.abc.ResourceReader
importlib.abc.Traversable
importlib.abc.TraversableResources
使用
importlib.resources.abc
类代替:(由 Jason R. Coombs 和 Hugo van Kemenade 在 gh-93963 中贡献。)
itertools
具有对 copy, deepcopy 和 pickle 等操作的未写入文档的、低效的、历史上充满问题的且不稳定的支持。 这将在 3.14 中移除以显著减少代码量和维护负担。 (由 Raymond Hettinger 在 gh-101588 中贡献。)multiprocessing
: 默认的启动方法在目前默认使用'fork'
的 Linux, BSD 和其他非 macOS POSIX 平台上将改为更安全的方法 (gh-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 中贡献。)pty
:master_open()
: 使用pty.openpty()
。slave_open()
: 使用pty.openpty()
。
-
如果使用了 命名占位符 且 parameters 是一个序列而不是
dict
则选择execute()
和executemany()
。
urllib
:urllib.parse.Quoter
已被弃用:它不应被作为公有 API。 (由 Gregory P. Smith 在 gh-88168 中贡献。)
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 中贡献。)
-
未写入文档的用于创建
NamedTuple
类的关键字参数语法 (例如Point = NamedTuple("Point", x=int, y=int)
) 自 Python 3.13 起已被弃用。 请改用基于类的语法或函数语法。在使用
TypedDict
的函数式语法时,如果没有给 fields 参数传值(如TD = TypedDict("TD")
)或传入None``(如 ``TD = TypedDict("TD", None)
),该用法自 Python 3.13 起被弃用。如果要创建空字段的 TypedDict,应当改用class TD(TypedDict): pass``或 ``TD = TypedDict("TD", {})
语法。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 中贡献。)
-
对布尔类型
~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 Python 3.17¶
-
collections.abc.ByteString
is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)
to test ifobj
implements the buffer protocol at runtime. For use in type annotations, either useBuffer
or a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview
).ByteString
was originally intended to be an abstract class that would serve as a supertype of bothbytes
andbytearray
. However, since the ABC never had any methods, knowing that an object was an instance ofByteString
never actually told you anything useful about the object. Other common buffer types such asmemoryview
were also never understood as subtypes ofByteString
(either at runtime or by static type checkers).See PEP 688 for more details. (Contributed by Shantanu Jain in gh-91896.)
-
Before Python 3.14, old-style unions were implemented using the private class
typing._UnionGenericAlias
. This class is no longer needed for the implementation, but it has been retained for backward compatibility, with removal scheduled for Python 3.17. Users should use documented introspection helpers liketyping.get_origin()
andtyping.get_args()
instead of relying on private implementation details.typing.ByteString
, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)
to test ifobj
implements the buffer protocol at runtime. For use in type annotations, either useBuffer
or a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview
).ByteString
was originally intended to be an abstract class that would serve as a supertype of bothbytes
andbytearray
. However, since the ABC never had any methods, knowing that an object was an instance ofByteString
never actually told you anything useful about the object. Other common buffer types such asmemoryview
were also never understood as subtypes ofByteString
(either at runtime or by static type checkers).See PEP 688 for more details. (Contributed by Shantanu Jain in gh-91896.)
计划在未来版本中移除¶
以下API将会被移除,尽管具体时间还未确定。
argparse
: 嵌套参数分组和嵌套互斥分组的做法已被弃用。-
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
和FancyURLopener
方式已被弃用。 改用更新urlopen()
函数和方法。wsgiref
:SimpleHandler.stdout.write()
不应执行部分写入。xml.etree.ElementTree
: 对Element
的真值测试已被弃用。 在未来的发布版中它将始终返回True
。 建议改用显式的len(elem)
或elem is not None
测试。
C API 的弃用项¶
计划在 Python 3.14 中移除¶
PyDictObject
中的ma_version_tag
字段用于扩展模块 ( PEP 699 ; gh-101193 )。创建
immutable types
的可变基础 ( 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_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 中的待移除功能¶
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()
。_PyErr_ChainExceptions()
: 改用_PyErr_ChainExceptions1()
。PyBytesObject.ob_shash
成员:改为调用PyObject_Hash()
。PyDictObject.ma_version_tag
成员。线程本地存储 (TLS) API: