弃用¶
计划在 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
CGIHTTPRequestHandler
has 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。typing.no_type_check_decorator()
装饰器自 Python 3.13 起已被弃用。 存在于typing
模块八年之后,它仍未被任何主要类型检查器所支持。
sre_compile
,sre_constants
和sre_parse
模块。wave
:The
getmark()
,setmark()
andgetmarkers()
methods of theWave_read
andWave_write
classes 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 起已被弃用,因为它会产生奇怪和不直观的结果 (-2
and-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 中移除¶
-
在Python 3.14 之前,旧式的联合是通过私有类
typing._UnionGenericAlias
实现的。 实现已不再需要该类,但为向后兼容性保留了该类,并计划在 Python 3.17 中删除。 用户应使用记录在案的内省助手函数,如typing.get_origin()
和typing.get_args()
,而不是依赖于私有的实现细节。
计划在 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 varioushashlib
implementations.Support for the
string
keyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
string
keyword 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.
计划在未来版本中移除¶
以下API将会被移除,尽管具体时间还未确定。
-
嵌套参数组和嵌套互斥组已被弃用 。
将未写入文档的关键字参数 prefix_chars 传递给
add_argument_group()
的做法现在已被弃用。argparse.FileType
类型转换器已弃用 。
-
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 中贡献。)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_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()
。
内部类
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()
和PyWeakref_GET_OBJECT()
: 改用PyWeakref_GetRef()
。 在 Python 3.12 及更旧的版本中可以使用 pythoncapi-compat 项目 来获取PyWeakref_GetRef()
。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 thePYTHONHOME
environment 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()
: 改为清除sys.warnoptions
和warnings.filters
。
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_level
orPyConfig_Get("optimization_level")
。Py_NoSiteFlag
: 改用PyConfig.site_import
或PyConfig_Get("site_import")
。Py_BytesWarningFlag
: 改用PyConfig.bytes_warning
orPyConfig_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 中移除¶
弃用的私有函数 (gh-128863):
_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_WriteUTF8(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()
。
在 Python 3.13 和更旧的版本中可以使用 pythoncapi-compat 项目 来获取这些新的公有函数。
Pending removal in Python 3.20¶
The
cval
field inPyComplexObject
(gh-128813). UsePyComplex_AsCComplex()
andPyComplex_FromCComplex()
to convert a Python complex number to/from the CPy_complex
representation.
计划在未来版本中移除¶
以下 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: