弃用¶
计划在 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 起已被弃用。
-
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.用于 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()has been deprecated since Python 3.13. Useos.path.isreserved()to detect reserved paths on Windows.
-
platform.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.
-
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 起已被弃用。 请改用class TD(TypedDict): pass或TD = TypedDict("TD", {})来创建一个零字段的 TypedDict。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.
sre_compile,sre_constants和sre_parse模块。wave:The
getmark(),setmark()andgetmarkers()methods of theWave_readandWave_writeclasses have been deprecated since Python 3.13.
-
zipimport.zipimporter.load_module()has been deprecated since Python 3.10. Useexec_module()instead. (gh-125746.)
计划在 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()。 (由李佳昊和 Kumar Aditya 在 gh-122875 中贡献。)asyncio策略系统已被弃用并将在 Python 3.16 中移除。 具体而言,是弃用了下列类和函数:用户应当使用
asyncio.run()或asyncio.Runner并附带 loop_factory 以使用想要的事件循环实现。例如,在 Windows 上使用
asyncio.SelectorEventLoop:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(由 Kumar Aditya 在 gh-127949 中贡献。)
-
对布尔类型
~True或~False执行按位取反的操作自 Python 3.12 起已被弃用,因为它会产生奇怪和不直观的结果 (-2and-1)。 请改用not x来对布尔值执行逻辑否操作。 对于需要对下层整数执行按位取反操作的少数场合,请显式地将其转换为int(~int(x))。
-
调用
functools.reduce()的 Python 实现并传入 function 或 sequence 作为关键字参数的做法自 Python 3.14 起已被弃用。
-
使用 strm 参数对自定义日志记录处理器提供支持的做法已被弃用并计划在 Python 3.16 中移除。 改为使用 stream 参数定义处理器。 (由 Mariusz Felisiak 在 gh-115032 中贡献。)
-
有效扩展以 ". " 开头或在
mimetypes.MimeTypes.add_type()为空。 未加点的扩展已弃用,在 Python 3.16 中将引发ValueError。 (由 Hugo van Kemenade 在 gh-75223 中贡献。)
-
ExecError异常自 Python 3.14 起已被弃用。 它自 Python 3.4 起就未被shutil中的任何函数所使用,现在是RuntimeError的一个别名。
-
Class.get_methods方法自 Python 3.14 起被弃用。
sys:_enablelegacywindowsfsencoding()函数自 Python 3.13 起被弃用。 请改用PYTHONLEGACYWINDOWSFSENCODING环境变量。
-
自Python 3.14 起,
sysconfig.expand_makefile_vars()函数已被弃用。请使用sysconfig.get_paths()的vars参数代替。
-
未写入文档也未被使用的
TarFile.tarfile属性自 Python 3.13 起被弃用。
计划在 Python 3.17 中移除¶
-
collections.abc.ByteString计划在 Python 3.17 中移除。使用
isinstance(obj, collections.abc.Buffer)来测试obj是否在运行时实现了 缓冲区协议。 要用于类型标注,则使用Buffer或是显式指明你的代码所支持类型的并集 (例如bytes | bytearray | memoryview)。ByteString原本是想作为bytes和bytearray的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是ByteString的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如memoryview同样不能被当作是ByteString的子类型(无论是在运行时还是对于静态类型检查器)。
-
在Python 3.14 之前,旧式的联合是通过私有类
typing._UnionGenericAlias实现的。 实现已不再需要该类,但为向后兼容性保留了该类,并计划在 Python 3.17 中删除。 用户应使用记录在案的内省助手函数,如typing.get_origin()和typing.get_args(),而不是依赖于私有的实现细节。typing.ByteString自 Python 3.9 起已被弃用,计划在 Python 3.17 中移除。使用
isinstance(obj, collections.abc.Buffer)来测试obj是否在运行时实现了 缓冲区协议。 要用于类型标注,则使用Buffer或是显式指明你的代码所支持类型的并集 (例如bytes | bytearray | memoryview)。ByteString原本是想作为bytes和bytearray的超类型的抽象基类提供。 不过,由于 ABC 不能有任何方法,知道一个对象是ByteString的实例并不能真正告诉你有关该对象的任何有用信息。 其他常见缓冲区类型如memoryview同样不能被当作是ByteString的子类型(无论是在运行时还是对于静态类型检查器)。
计划在 Python 3.19 中移除¶
-
In hash function constructors such as
new()or the direct hash-named constructors such asmd5()andsha256(), their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in varioushashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword parameter was not correctly supported depending on the backend implementation of hash functions. Prefer passing the initial data as a positional argument for maximum backwards compatibility.
Pending removal in Python 3.20¶
The
__version__attribute has been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)logging(__date__also deprecated)
(Contributed by Hugo van Kemenade and Stan Ulbrych in gh-76007.)
计划在未来版本中移除¶
以下API将会被移除,尽管具体时间还未确定。
-
嵌套参数组和嵌套互斥组已被弃用 。
将未写入文档的关键字参数 prefix_chars 传递给
add_argument_group()的做法现在已被弃用。argparse.FileType类型转换器已弃用 。
-
生成器:
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 中贡献。)codecs:codecs.open()请改用open()。 (gh-133038)-
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 中贡献。)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
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._UnionGenericAlias不再用于实现typing.Union。为了保护使用该私有类的用户的兼容性 ,将至少在 Python 3.17 之前提供兼容性。 (由 Jelle Zijlstra 在 gh-105499 中贡献)。unittest.IsolatedAsyncioTestCase: 从测试用例返回不为None的值的做法已被弃用。urllib.parse函数已被弃用:改用urlparse()splitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()不应执行部分写入。xml.etree.ElementTree: 对Element的真值测试已被弃用。 在未来的发布版中它将始终返回True。 建议改用显式的len(elem)或elem is not None测试。sys._clear_type_cache()已弃用,请改用sys._clear_internal_caches()。
C API 的弃用项¶
计划在 Python 3.15 中移除¶
The
PyImport_ImportModuleNoBlock(): UsePyImport_ImportModule()instead.PyWeakref_GetObject()andPyWeakref_GET_OBJECT(): UsePyWeakref_GetRef()instead. The pythoncapi-compat project can be used to getPyWeakref_GetRef()on Python 3.12 and older.Py_UNICODE类型和Py_UNICODE_WIDE宏:改用wchar_t。PyUnicode_AsDecodedObject(): 改用PyCodec_Decode()。PyUnicode_AsDecodedUnicode(): 改用PyCodec_Decode();请注意某些编解码器 (例如 "base64") 可能返回str以外的类型,比如bytes。PyUnicode_AsEncodedObject(): 改用PyCodec_Encode()。PyUnicode_AsEncodedUnicode(): 使用PyCodec_Encode()代替;请注意,某些编解码器(如 "base64")可能返回bytes之外的类型,如str。Python 初始化函数, Python 3.13 中弃用:
Py_GetPath(): UsePyConfig_Get("module_search_paths")(sys.path) instead.Py_GetPrefix(): UsePyConfig_Get("base_prefix")(sys.base_prefix) instead. UsePyConfig_Get("prefix")(sys.prefix) if virtual environments need to be handled.Py_GetExecPrefix(): UsePyConfig_Get("base_exec_prefix")(sys.base_exec_prefix) instead. UsePyConfig_Get("exec_prefix")(sys.exec_prefix) if virtual environments need to be handled.Py_GetProgramFullPath(): UsePyConfig_Get("executable")(sys.executable) instead.Py_GetProgramName(): UsePyConfig_Get("executable")(sys.executable) instead.Py_GetPythonHome(): UsePyConfig_Get("home")or thePYTHONHOMEenvironment variable instead.
在 Python 3.13 和更旧的版本中可以使用 pythoncapi-compat 项目 来获取
PyConfig_Get()。用于配置 Python 的初始化的函数,在 Python 3.11 中已弃用:
PySys_SetArgvEx(): 改为设置PyConfig.argv。PySys_SetArgv(): 改为设置PyConfig.argv。Py_SetProgramName(): 改为设置PyConfig.program_name。Py_SetPythonHome(): 改为设置PyConfig.home。PySys_ResetWarnOptions(): Clearsys.warnoptionsandwarnings.filtersinstead.
Py_InitializeFromConfig()API 应与PyConfig一起使用。全局配置变量:
Py_DebugFlag: 改用PyConfig.parser_debug或PyConfig_Get("parser_debug")。Py_VerboseFlag: 改用PyConfig.verbose或PyConfig_Get("verbose")。Py_InteractiveFlag: 改用PyConfig.interactive或PyConfig_Get("interactive")。Py_InspectFlag: 改用PyConfig.inspect或PyConfig_Get("inspect")。Py_OptimizeFlag: 改用PyConfig.optimization_levelorPyConfig_Get("optimization_level")。Py_NoSiteFlag: 改用PyConfig.site_import或PyConfig_Get("site_import")。Py_BytesWarningFlag: 改用PyConfig.bytes_warningorPyConfig_Get("bytes_warning")。Py_FrozenFlag: 使用PyConfig.pathconfig_warnings或PyConfig_Get("pathconfig_warnings")代替。Py_IgnoreEnvironmentFlag: 使用PyConfig.use_environment或PyConfig_Get("use_environment")代替。Py_DontWriteBytecodeFlag: 使用PyConfig.write_bytecode或PyConfig_Get("write_bytecode")代替。Py_NoUserSiteDirectory: 使用PyConfig.user_site_directory或PyConfig_Get("user_site_directory")代替。Py_UnbufferedStdioFlag: 使用PyConfig.buffered_stdio或PyConfig_Get("buffered_stdio")代替。Py_HashRandomizationFlag: 使用PyConfig.use_hash_seed和PyConfig.hash_seed或PyConfig_Get("hash_seed")代替。Py_IsolatedFlag: 使用PyConfig.isolated或PyConfig_Get("isolated")代替。Py_LegacyWindowsFSEncodingFlag: 使用PyPreConfig.legacy_windows_fs_encoding或PyConfig_Get("legacy_windows_fs_encoding")代替。Py_LegacyWindowsStdioFlag: 使用PyConfig.legacy_windows_stdio或PyConfig_Get("legacy_windows_stdio")代替。Py_FileSystemDefaultEncoding,:c:var:!Py_HasFileSystemDefaultEncoding: 使用PyConfig.filesystem_encoding或PyConfig_Get("filesystem_encoding")代替。Py_FileSystemDefaultEncodeErrors: 使用PyConfig.filesystem_errors或PyConfig_Get("filesystem_errors")代替。Py_UTF8Mode: 使用PyPreConfig.utf8_mode或PyConfig_Get("utf8_mode")代替。 (参见Py_PreInitialize())。
Py_InitializeFromConfig()API 应与PyConfig一起使用,以设置这些选项。 或者使用PyConfig_Get()在运行时获取这些选项。
计划在 Python 3.18 中移除¶
以下私有函数已被弃用,并计划在 Python 3.18 中移除:
_PyBytes_Join(): 使用PyBytes_Join()。_PyDict_GetItemStringWithError(): 使用PyDict_GetItemStringRef()。_PyDict_Pop(): 使用PyDict_Pop()。_PyLong_Sign(): 使用PyLong_GetSign()。_PyLong_FromDigits()和_PyLong_New(): 使用PyLongWriter_Create()。_PyThreadState_UncheckedGet(): 使用PyThreadState_GetUnchecked()。_PyUnicode_AsString(): 使用PyUnicode_AsUTF8()。_PyUnicodeWriter_Init(): 将_PyUnicodeWriter_Init(&writer)替换为writer = PyUnicodeWriter_Create(0)。_PyUnicodeWriter_Finish(): 将_PyUnicodeWriter_Finish(&writer)替换为PyUnicodeWriter_Finish(writer)。_PyUnicodeWriter_Dealloc(): 将_PyUnicodeWriter_Dealloc(&writer)替换为PyUnicodeWriter_Discard(writer)。_PyUnicodeWriter_WriteChar(): 将_PyUnicodeWriter_WriteChar(&writer, ch)替换为PyUnicodeWriter_WriteChar(writer, ch)._PyUnicodeWriter_WriteStr(): 将_PyUnicodeWriter_WriteStr(&writer, str)替换为PyUnicodeWriter_WriteStr(writer, str)。_PyUnicodeWriter_WriteSubstring(): 将_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)替换为PyUnicodeWriter_WriteSubstring(writer, str, start, end)。_PyUnicodeWriter_WriteASCIIString(): 请将_PyUnicodeWriter_WriteASCIIString(&writer, str)替换为PyUnicodeWriter_WriteASCII(writer, str)。_PyUnicodeWriter_WriteLatin1String(): 将_PyUnicodeWriter_WriteLatin1String(&writer, str)替换为PyUnicodeWriter_WriteUTF8(writer, str)。_PyUnicodeWriter_Prepare(): (无替代)。_PyUnicodeWriter_PrepareKind(): (无替代)。_Py_HashPointer():使用Py_HashPointer()。_Py_fopen_obj():使用Py_fopen()。
pythoncapi-compat 项目 可被用于在 Python 3.13 及更早版本中获取这些新的公有函数。 (由 Victor Stinner 在 gh-128863 中贡献。)
Pending removal in Python 3.20¶
The
cvalfield inPyComplexObject(gh-128813). UsePyComplex_AsCComplex()andPyComplex_FromCComplex()to convert a Python complex number to/from the CPy_complexrepresentation.
计划在未来版本中移除¶
以下 API 已被弃用,将被移除,但目前尚未确定移除日期。
Py_TPFLAGS_HAVE_FINALIZE: 自 Python 3.8 起不再需要。PySlice_GetIndicesEx(): 改用PySlice_Unpack()andPySlice_AdjustIndices()。PyUnicode_READY(): 自 Python 3.12 起不再需要PyErr_Display(): 改用PyErr_DisplayException()。_PyErr_ChainExceptions(): 改用_PyErr_ChainExceptions1()。PyBytesObject.ob_shash成员:改为调用PyObject_Hash()。线程本地存储 (TLS) API: