弃用¶
计划在 Python 3.14 中移除¶
argparse:argparse.BooleanOptionalAction的 type, choices 和 metavar 形参已被弃用并将在 3.14 中移除。 (由 Nikita Sobolev 在 gh-92248 中贡献。)ast: 以下特性自 Python 3.8 起已在文档中声明弃用,现在当运行时如果它们被访问或使用时将发出DeprecationWarning,并将在 Python 3.14 中移除:ast.Numast.Strast.Bytesast.NameConstantast.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 中贡献。)
collections.abc: 已弃用ByteString。 推荐改用Sequence或Buffer。 用于类型标注时,则推荐并集运算符,如bytes | bytearray,或collections.abc.Buffer。 (由 Shantanu Jain 在 gh-91896 中贡献。)email: 已弃用email.utils.localtime()中的 isdst 形参。 (由 Alan Williams 在 gh-72346 中贡献。)importlib:__package__和__cached__将不再被设置或是被导入系统纳入考量 (gh-97879)。importlib.abc中已弃用的类:importlib.abc.ResourceReaderimportlib.abc.Traversableimportlib.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()。date 和 datetime 适配器,date 和 timestamp 转换器:请参阅
sqlite3文档了解推荐的替代方案。
types.CodeType: 访问co_lnotab的做法自 3.10 起已在 PEP 626 中被弃用并曾计划在 3.12 中移除,但实际上在 3.12 中仅设置了DeprecationWarning。 可能会在 3.14 中移除。 (由 Nikita Sobolev 在 gh-101866 中贡献。)typing:ByteString自 Python 3.9 起已被弃用,现在当被使用时将会发出DeprecationWarning。urllib:urllib.parse.Quoter已被弃用:它不应被作为公有 API。 (由 Gregory P. Smith 在 gh-88168 中贡献。)
Python 3.15 中的待移除功能¶
-
The undocumented
ctypes.SetPointerType()function has been deprecated since Python 3.13.
-
The obsolete and rarely used
CGIHTTPRequestHandlerhas been deprecated since Python 3.13. No direct replacement exists. Anything is better than CGI to interface a web server with a request handler.The
--cgiflag to the python -m http.server command-line interface has been deprecated since Python 3.13.
-
The
getdefaultlocale()function has been deprecated since Python 3.11. Its removal was originally planned for Python 3.13 (gh-90817), but has been postponed to Python 3.15. Usegetlocale(),setlocale(), andgetencoding()instead. (Contributed by Hugo van Kemenade in gh-111187.)
-
PurePath.is_reserved()has been deprecated since Python 3.13. Useos.path.isreserved()to detect reserved paths on Windows.
-
java_ver()has been deprecated since Python 3.13. This function is only useful for Jython support, has a confusing API, and is largely untested.
-
RLock()will take no arguments in Python 3.15. Passing any arguments has been deprecated since Python 3.14, as the Python version does not permit any arguments, but the C version allows any number of positional or keyword arguments, ignoring every argument.
-
The undocumented keyword argument syntax for creating
NamedTupleclasses (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.The
typing.no_type_check_decorator()decorator function has been deprecated since Python 3.13. After eight years in thetypingmodule, it has yet to be supported by any major type checker.
wave:The
getmark(),setmark(), andgetmarkers()methods of theWave_readandWave_writeclasses have been deprecated since Python 3.13.
计划在 Python 3.16 中移除¶
-
Bitwise inversion on boolean types,
~Trueor~Falsehas been deprecated since Python 3.12, as it produces surprising and unintuitive results (-2and-1). Usenot xinstead for the logical negation of a Boolean. In the rare case that you need the bitwise inversion of the underlying integer, convert tointexplicitly (~int(x)).
-
The
'u'format code (wchar_t) has been deprecated in documentation since Python 3.3 and at runtime since Python 3.13. Use the'w'format code (Py_UCS4) for Unicode characters instead.
-
The
ExecErrorexception has been deprecated since Python 3.14. It has not been used by any function inshutilsince Python 3.4, and is now an alias ofRuntimeError.
-
The
Class.get_methodsmethod has been deprecated since Python 3.14.
sys:The
_enablelegacywindowsfsencoding()function has been deprecated since Python 3.13. Use thePYTHONLEGACYWINDOWSFSENCODINGenvironment variable instead.
-
The undocumented and unused
TarFile.tarfileattribute has been deprecated since Python 3.13.
计划在未来版本中移除¶
以下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: 复数值必须是一个整数。-
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 中贡献。)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_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.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()。
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(): SetPyConfig.argvinstead.PySys_SetArgv(): SetPyConfig.argvinstead.Py_SetProgramName(): SetPyConfig.program_nameinstead.Py_SetPythonHome(): SetPyConfig.homeinstead.
Py_InitializeFromConfig()API 应与PyConfig一起使用。全局配置变量:
Py_DebugFlag: UsePyConfig.parser_debuginstead.Py_VerboseFlag: UsePyConfig.verboseinstead.Py_QuietFlag: UsePyConfig.quietinstead.Py_InteractiveFlag: UsePyConfig.interactiveinstead.Py_InspectFlag: UsePyConfig.inspectinstead.Py_OptimizeFlag: UsePyConfig.optimization_levelinstead.Py_NoSiteFlag: UsePyConfig.site_importinstead.Py_BytesWarningFlag: UsePyConfig.bytes_warninginstead.Py_FrozenFlag: UsePyConfig.pathconfig_warningsinstead.Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentinstead.Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeinstead.Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryinstead.Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioinstead.Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedinstead.Py_IsolatedFlag: UsePyConfig.isolatedinstead.Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodinginstead.Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioinstead.Py_FileSystemDefaultEncoding: UsePyConfig.filesystem_encodinginstead.Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodinginstead.Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsinstead.Py_UTF8Mode: UsePyPreConfig.utf8_modeinstead. (seePy_PreInitialize())
Py_InitializeFromConfig()API 应与PyConfig一起使用。
Python 3.15 中的待移除功能¶
捆绑的
libmpdecimal副本。The
PyImport_ImportModuleNoBlock(): UsePyImport_ImportModule()instead.PyWeakref_GetObject()andPyWeakref_GET_OBJECT(): UsePyWeakref_GetRef()instead.Py_UNICODEtype and thePy_UNICODE_WIDEmacro: Usewchar_tinstead.Python 初始化函数
PySys_ResetWarnOptions(): Clearsys.warnoptionsandwarnings.filtersinstead.Py_GetExecPrefix(): Getsys.exec_prefixinstead.Py_GetPath(): Getsys.pathinstead.Py_GetPrefix(): Getsys.prefixinstead.Py_GetProgramFullPath(): Getsys.executableinstead.Py_GetProgramName(): Getsys.executableinstead.Py_GetPythonHome(): GetPyConfig.homeor thePYTHONHOMEenvironment variable instead.
计划在未来版本中移除¶
以下 API 已被弃用,将被移除,但目前尚未确定移除日期。
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch(): UsePyErr_GetRaisedException()instead.PyErr_NormalizeException(): UsePyErr_GetRaisedException()instead.PyErr_Restore(): UsePyErr_SetRaisedException()instead.PyModule_GetFilename(): UsePyModule_GetFilenameObject()instead.PyOS_AfterFork(): UsePyOS_AfterFork_Child()instead.PySlice_GetIndicesEx(): UsePySlice_Unpack()andPySlice_AdjustIndices()instead.PyUnicode_AsDecodedObject(): UsePyCodec_Decode()instead.PyUnicode_AsDecodedUnicode(): UsePyCodec_Decode()instead.PyUnicode_AsEncodedObject(): UsePyCodec_Encode()instead.PyUnicode_AsEncodedUnicode(): UsePyCodec_Encode()instead.PyUnicode_READY(): Unneeded since Python 3.12PyErr_Display(): UsePyErr_DisplayException()instead._PyErr_ChainExceptions(): Use_PyErr_ChainExceptions1()instead.PyBytesObject.ob_shash成员:改为调用PyObject_Hash()。PyDictObject.ma_version_tag成员。线程本地存储 (TLS) API:
PyThread_create_key(): UsePyThread_tss_alloc()instead.PyThread_delete_key(): UsePyThread_tss_free()instead.PyThread_set_key_value(): UsePyThread_tss_set()instead.PyThread_get_key_value(): UsePyThread_tss_get()instead.PyThread_delete_key_value(): UsePyThread_tss_delete()instead.PyThread_ReInitTLS(): Unneeded since Python 3.7.