棄用項¶
計劃在 Python 3.15 中移除¶
匯入系統
在設定模組的
__cached__
屬性時,若未同時設定__spec__.cached
,此行為已被棄用。在 Python 3.15 中,匯入系統或標準庫將不再設定或考慮__cached__
屬性。(由 gh-97879 貢獻)在設定模組的
__package__
屬性時,若未同時設定__spec__.parent
,此行為已被棄用。在 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 起棄用。要檢測 Windows 上的保留路徑,請使用os.path.isreserved()
。
-
java_ver()
已自 Python 3.13 起棄用。此函式僅對 Jython 支援有用,其 API 令人困惑,且基本未經測試。
-
sysconfig.is_python_build()
的 check_home 引數已自 Python 3.12 起棄用。
-
RLock()
在 Python 3.15 中將不再接受任何引數。自 Python 3.14 起,傳遞任何引數的行為已被棄用,因為 Python 版本不允許任何引數,但 C 版本允許任意數量的位置或關鍵字引數,並會忽略所有引數。
-
types.CodeType
:訪問co_lnotab
已在 PEP 626 中自 3.10 版起棄用,並計劃在 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 起棄用。
-
load_module()
已自 Python 3.10 起棄用。請改用exec_module()
。(由 Jiahao Li 在 gh-125746 中貢獻。)
計劃在 Python 3.16 中移除¶
匯入系統
在設定模組的
__loader__
屬性時,若未同時設定__spec__.loader
,此行為已被棄用。在 Python 3.16 中,匯入系統或標準庫將不再設定或考慮__loader__
屬性。
-
'u'
格式程式碼(wchar_t
)自 Python 3.3 起在文件中被棄用,自 Python 3.13 起在執行時被棄用。請改用'w'
格式程式碼(Py_UCS4
)來處理 Unicode 字元。
-
asyncio.iscoroutinefunction()
已被棄用,並將在 Python 3.16 中移除;請改用inspect.iscoroutinefunction()
。(由 Jiahao Li 和 Kumar Aditya 在 gh-122875 中貢獻。)asyncio
的策略系統已被棄用,並將在 Python 3.16 中移除。特別是,以下類和函式已被棄用:使用者應使用
asyncio.run()
或帶 loop_factory 引數的asyncio.Runner
來使用期望的事件迴圈實現。例如,在 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
和-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
環境變數。
-
sysconfig.expand_makefile_vars()
函式已自 Python 3.14 起棄用。請改用sysconfig.get_paths()
的vars
引數。
-
未寫入文件且未使用的
TarFile.tarfile
屬性已自 Python 3.13 起棄用。
計劃在 Python 3.17 中移除¶
-
collections.abc.ByteString
計劃在 Python 3.17 中移除。要測試
obj
是否在執行時實現了緩衝區協議,請使用isinstance(obj, collections.abc.Buffer)
。在型別註解中,請使用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 中移除。要測試
obj
是否在執行時實現了緩衝區協議,請使用isinstance(obj, collections.abc.Buffer)
。在型別註解中,請使用Buffer
或顯式指定程式碼支援的型別的聯合型別(例如bytes | bytearray | memoryview
)。ByteString
最初旨在作為一個抽象類,作為bytes
和bytearray
的超型別。然而,由於該抽象基類(ABC)從未有過任何方法,所以知道一個物件是ByteString
的例項實際上並不能提供任何關於該物件的有用資訊。其他常見的緩衝區型別,如memoryview
,也從未被理解為ByteString
的子型別(無論是在執行時還是透過靜態型別檢查器)。
計劃在 Python 3.19 中移除¶
計劃在未來版本中移除¶
以下 API 將在未來移除,但目前尚未確定移除日期。
-
巢狀引數組和巢狀互斥組的做法已被棄用。
向
add_argument_group()
傳遞未寫入文件的關鍵字引數 prefix_chars 的做法現已棄用。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
:請使用open()
而不是codecs.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 中貢獻。)sre_compile
、sre_constants
和sre_parse
模組。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()
。
內部類
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 中移除¶
PyWeakref_GetObject()
和PyWeakref_GET_OBJECT()
:請改用PyWeakref_GetRef()
。可以使用 pythoncapi-compat 專案 在 Python 3.12 及更早版本中獲得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()
:請改用PyConfig_Get("module_search_paths")
(sys.path
)。Py_GetPrefix()
:請改用PyConfig_Get("base_prefix")
(sys.base_prefix
)。如果需要處理虛擬環境,請使用PyConfig_Get("prefix")
(sys.prefix
)。Py_GetExecPrefix()
:請改用PyConfig_Get("base_exec_prefix")
(sys.base_exec_prefix
)。如果需要處理虛擬環境,請使用PyConfig_Get("exec_prefix")
(sys.exec_prefix
)。Py_GetProgramFullPath()
:請改用PyConfig_Get("executable")
(sys.executable
)。Py_GetProgramName()
:請改用PyConfig_Get("executable")
(sys.executable
)。Py_GetPythonHome()
:請改用PyConfig_Get("home")
或PYTHONHOME
環境變數。
可以使用 pythoncapi-compat 專案 在 Python 3.13 及更早版本中獲得
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
或PyConfig_Get("optimization_level")
。Py_NoSiteFlag
:請改用PyConfig.site_import
或PyConfig_Get("site_import")
。Py_BytesWarningFlag
:請改用PyConfig.bytes_warning
或PyConfig_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
、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 中貢獻。)
計劃在未來版本中移除¶
以下 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()
。執行緒本地儲存 (TLS) API