已棄用項目¶
Pending removal in Python 3.15¶
引入系統 (import system):
在模組上設定
__cached__
而沒有設定__spec__.cached
的做法已被棄用。在 Python 3.15 中,引入系統或標準函式庫將不再設定或考慮__cached__
。(gh-97879)在模組上設定
__package__
而沒有設定__spec__.parent
的做法已被棄用。在 Python 3.15 中,引入系統或標準函式庫將不再設定或考慮__package__
。(gh-97879)
-
自 Python 3.13 起,未記錄的
ctypes.SetPointerType()
函式已被棄用。
-
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 3.13 起,python -m http.server 命令列介面的
--cgi
旗標已被棄用。
-
load_module()
method:請改用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 起已被棄用。
-
RLock()
在 Python 3.15 中將不接受任何引數。自 Python 3.14 起,傳遞任何引數的用法已被棄用,因為 Python 版本不允許任何引數,但 C 版本允許任意數量的位置或關鍵字引數,並忽略每個引數。
-
types.CodeType
:自 3.10 起,存取co_lnotab
已在 PEP 626 中被棄用,並計劃在 3.12 中移除,但只在 3.12 中於適當時發出DeprecationWarning
。可能在 3.15 中移除。(由 Nikita Sobolev 於 gh-101866 貢獻。)
-
The undocumented keyword argument syntax for creating
NamedTuple
classes (for example,Point = NamedTuple("Point", x=int, y=int)
) has been deprecated since Python 3.13. Use the class-based syntax or the functional syntax instead.當使用
TypedDict
的函式語法時,未傳遞值給 fields 參數 (TD = TypedDict("TD")
) 或傳遞None
(TD = TypedDict("TD", None)
) 的做法自 Python 3.13 起已被棄用。請使用class TD(TypedDict): pass
或TD = TypedDict("TD", {})
來建立具有零個欄位的 TypedDict。自 Python 3.13 起,
typing.no_type_check_decorator()
裝飾器函式已被棄用。在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 中待移除的項目¶
引入系統 (import system):
在模組上設定
__loader__
而沒有設定__spec__.loader
的做法將於 Python 3.16 被棄用。在 Python 3.16 中,引入系統或標準函式庫將不再設定或考慮__loader__
。
-
自 Python 3.3 起,
'u'
格式碼 (wchar_t
) 在文件中已被棄用,自 Python 3.13 起在 runtime 已被棄用。請使用'w'
格式碼 (Py_UCS4
) 來取代 Unicode 字元。
-
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.)asyncio
policy system is deprecated and will be removed in Python 3.16. In particular, the following classes and functions are deprecated:Users should use
asyncio.run()
orasyncio.Runner
with loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoop
on Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(Contributed by Kumar Aditya in gh-127949.)
-
自 Python 3.12 起,布林型別的位元反轉
~True
或~False
已被棄用,因為它會產生不預期且不直觀的結果(-2
和-1
)。使用not x
代替布林值的邏輯否定。在極少數情況下,你需要對底層的整數進行位元反轉,請明確轉換為~int(x)
(~int(x)
)。
-
Calling the Python implementation of
functools.reduce()
with function or sequence as keyword arguments has been deprecated since Python 3.14.
-
Support for custom logging handlers with the strm argument is deprecated and scheduled for removal in Python 3.16. Define handlers with the stream argument instead. (Contributed by Mariusz Felisiak in gh-115032.)
-
Valid extensions start with a '.' or are empty for
mimetypes.MimeTypes.add_type()
. Undotted extensions are deprecated and will raise aValueError
in Python 3.16. (Contributed by Hugo van Kemenade in gh-75223.)
-
自 Python 3.14 起,
ExecError
例外已被棄用。自 Python 3.4 以來,它尚未被shutil
中的任何函式使用,現在是RuntimeError
的別名。
-
自 Python 3.14 起,
Class.get_methods
方法已被棄用。
sys
:自 Python 3.13 起,
_enablelegacywindowsfsencoding()
函式已被棄用。請改用PYTHONLEGACYWINDOWSFSENCODING
環境變數。
-
The
sysconfig.expand_makefile_vars()
function has been deprecated since Python 3.14. Use thevars
argument ofsysconfig.get_paths()
instead.
-
自 Python 3.13 起,未以文件記錄和未被使用的
TarFile.tarfile
屬性已被棄用。
Pending removal in Python 3.17¶
-
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.
Pending removal in 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.
Pending removal in future versions¶
以下 API 將在未來被移除,雖然目前尚未安排移除日期。
-
Nesting argument groups and nesting mutually exclusive groups are deprecated.
Passing the undocumented keyword argument prefix_chars to
add_argument_group()
is now deprecated.The
argparse.FileType
type converter is 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
的嚴格子類別實例。將
int()
委派給__trunc__()
方法。在
complex()
建構子中將複數作為 real 或 imag 引數傳遞現在已被棄用;它應該只作為單個位置引數傳遞。 (由 Serhiy Storchaka 於 gh-109218 貢獻。)
calendar
:calendar.January
和calendar.February
常數已被棄用並被calendar.JANUARY
和calendar.FEBRUARY
取代。 (由 Prince Roshan 於 gh-103636 貢獻。)codecs
: useopen()
instead ofcodecs.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
已被棄用。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()
。
The internal class
typing._UnionGenericAlias
is no longer used to implementtyping.Union
. To preserve compatibility with users using this private class, a compatibility shim will be provided until at least Python 3.17. (Contributed by Jelle Zijlstra in 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()
is deprecated: usesys._clear_internal_caches()
instead.
C API deprecations¶
Pending removal in 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()
: UsePyCodec_Decode()
instead; Note that some codecs (for example, "base64") may return a type other thanstr
, such asbytes
.PyUnicode_AsEncodedObject()
:請改用PyCodec_Encode()
。PyUnicode_AsEncodedUnicode()
: UsePyCodec_Encode()
instead; Note that some codecs (for example, "base64") may return a type other thanbytes
, such asstr
.Python initialization functions, deprecated in 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.
The pythoncapi-compat project can be used to get
PyConfig_Get()
on Python 3.13 and older.設定 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
: UsePyConfig.parser_debug
orPyConfig_Get("parser_debug")
instead.Py_VerboseFlag
: UsePyConfig.verbose
orPyConfig_Get("verbose")
instead.Py_QuietFlag
: UsePyConfig.quiet
orPyConfig_Get("quiet")
instead.Py_InteractiveFlag
: UsePyConfig.interactive
orPyConfig_Get("interactive")
instead.Py_InspectFlag
: UsePyConfig.inspect
orPyConfig_Get("inspect")
instead.Py_OptimizeFlag
: UsePyConfig.optimization_level
orPyConfig_Get("optimization_level")
instead.Py_NoSiteFlag
: UsePyConfig.site_import
orPyConfig_Get("site_import")
instead.Py_BytesWarningFlag
: UsePyConfig.bytes_warning
orPyConfig_Get("bytes_warning")
instead.Py_FrozenFlag
: UsePyConfig.pathconfig_warnings
orPyConfig_Get("pathconfig_warnings")
instead.Py_IgnoreEnvironmentFlag
: UsePyConfig.use_environment
orPyConfig_Get("use_environment")
instead.Py_DontWriteBytecodeFlag
: UsePyConfig.write_bytecode
orPyConfig_Get("write_bytecode")
instead.Py_NoUserSiteDirectory
: UsePyConfig.user_site_directory
orPyConfig_Get("user_site_directory")
instead.Py_UnbufferedStdioFlag
: UsePyConfig.buffered_stdio
orPyConfig_Get("buffered_stdio")
instead.Py_HashRandomizationFlag
: UsePyConfig.use_hash_seed
andPyConfig.hash_seed
orPyConfig_Get("hash_seed")
instead.Py_IsolatedFlag
: UsePyConfig.isolated
orPyConfig_Get("isolated")
instead.Py_LegacyWindowsFSEncodingFlag
: UsePyPreConfig.legacy_windows_fs_encoding
orPyConfig_Get("legacy_windows_fs_encoding")
instead.Py_LegacyWindowsStdioFlag
: UsePyConfig.legacy_windows_stdio
orPyConfig_Get("legacy_windows_stdio")
instead.Py_FileSystemDefaultEncoding
,Py_HasFileSystemDefaultEncoding
: UsePyConfig.filesystem_encoding
orPyConfig_Get("filesystem_encoding")
instead.Py_FileSystemDefaultEncodeErrors
: UsePyConfig.filesystem_errors
orPyConfig_Get("filesystem_errors")
instead.Py_UTF8Mode
: UsePyPreConfig.utf8_mode
orPyConfig_Get("utf8_mode")
instead. (seePy_PreInitialize()
)
The
Py_InitializeFromConfig()
API should be used withPyConfig
to set these options. OrPyConfig_Get()
can be used to get these options at runtime.
Pending removal in Python 3.18¶
Deprecated private functions (gh-128863):
_PyBytes_Join()
: usePyBytes_Join()
._PyDict_GetItemStringWithError()
: usePyDict_GetItemStringRef()
._PyDict_Pop()
:PyDict_Pop()
._PyLong_Sign()
: usePyLong_GetSign()
._PyLong_FromDigits()
and_PyLong_New()
: usePyLongWriter_Create()
._PyThreadState_UncheckedGet()
: usePyThreadState_GetUnchecked()
._PyUnicode_AsString()
: usePyUnicode_AsUTF8()
._PyUnicodeWriter_Init()
: replace_PyUnicodeWriter_Init(&writer)
withwriter = PyUnicodeWriter_Create(0)
._PyUnicodeWriter_Finish()
: replace_PyUnicodeWriter_Finish(&writer)
withPyUnicodeWriter_Finish(writer)
._PyUnicodeWriter_Dealloc()
: replace_PyUnicodeWriter_Dealloc(&writer)
withPyUnicodeWriter_Discard(writer)
._PyUnicodeWriter_WriteChar()
: replace_PyUnicodeWriter_WriteChar(&writer, ch)
withPyUnicodeWriter_WriteChar(writer, ch)
._PyUnicodeWriter_WriteStr()
: replace_PyUnicodeWriter_WriteStr(&writer, str)
withPyUnicodeWriter_WriteStr(writer, str)
._PyUnicodeWriter_WriteSubstring()
: replace_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)
withPyUnicodeWriter_WriteSubstring(writer, str, start, end)
._PyUnicodeWriter_WriteASCIIString()
: replace_PyUnicodeWriter_WriteASCIIString(&writer, str)
withPyUnicodeWriter_WriteUTF8(writer, str)
._PyUnicodeWriter_WriteLatin1String()
: replace_PyUnicodeWriter_WriteLatin1String(&writer, str)
withPyUnicodeWriter_WriteUTF8(writer, str)
._PyUnicodeWriter_Prepare()
: (no replacement)._PyUnicodeWriter_PrepareKind()
: (no replacement)._Py_HashPointer()
: usePy_HashPointer()
._Py_fopen_obj()
: usePy_fopen()
.
The pythoncapi-compat project can be used to get these new public functions on Python 3.13 and older.
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.
Pending removal in future versions¶
下列 API 已被棄用並將會被移除,不過目前尚未訂定移除日期。
Py_TPFLAGS_HAVE_FINALIZE
:自 Python 3.8 起不再需要PySlice_GetIndicesEx()
:請改用PySlice_Unpack()
和PySlice_AdjustIndices()
。PyUnicode_READY()
:自 Python 3.12 起不再需要PyErr_Display()
:請改用PyErr_DisplayException()
。_PyErr_ChainExceptions()
:請改用_PyErr_ChainExceptions1
。PyBytesObject.ob_shash
成員:請改為呼叫PyObject_Hash()
。執行緒局部儲存 (Thread Local Storage, TLS) API: