已棄用項目¶
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()
函式已被棄用。
-
過時且很少使用的
CGIHTTPRequestHandler
自 Python 3.13 起已被棄用。不存在直接的替代。任何東西都比 CGI 更好地將 Web 伺服器與請求處理程序介接起來。自 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()
已自 Python 3.13 被棄用。請用os.path.isreserved()
來偵測 Windows 上的保留路徑。
-
自 Python 3.13 起,
java_ver()
已被棄用。此函式僅對 Jython 支援有用,具有令人困惑的 API,基本上未經測試。
-
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 貢獻。)
-
用於建立
NamedTuple
類別的未以文件記錄之關鍵字引數語法 (Point = NamedTuple("Point", x=int, y=int)
) 已自 Python 3.13 棄用。請改用基於類別的語法或函式語法 (functional syntax)。當使用
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
模組中使用了八年之後,它尚未得到任何主要型別檢查器的支援。
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 中待移除的項目¶
引入系統 (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()
已被棄用並將在 Python 3.16 中移除;請改用inspect.iscoroutinefunction()
。(由 Jiahao Li 和 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 貢獻。)
-
自 Python 3.12 起,布林型別的位元反轉
~True
或~False
已被棄用,因為它會產生不預期且不直觀的結果(-2
和-1
)。使用not x
代替布林值的邏輯否定。在極少數情況下,你需要對底層的整數進行位元反轉,請明確轉換為~int(x)
(~int(x)
)。
-
自 Python 3.14 起,使用 function 或 sequence 關鍵字引數呼叫
functools.reduce()
的 Python 實作已被棄用。
-
對具有 strm 引數的自訂日誌記錄處理函式的支援已被棄用,並計劃在 Python 3.16 中移除。請改用 stream 引數。(由 Mariusz Felisiak 於 gh-115032 貢獻。)
-
有效的副檔名以 '.' 開頭或對
mimetypes.MimeTypes.add_type()
為空字串。未加點的副檔名已被棄用,並將在 Python 3.16 中引發ValueError
。(由 Hugo van Kemenade 於 gh-75223 貢獻。)
-
自 Python 3.14 起,
ExecError
例外已被棄用。自 Python 3.4 以來,它尚未被shutil
中的任何函式使用,現在是RuntimeError
的別名。
-
自 Python 3.14 起,
Class.get_methods
方法已被棄用。
sys
:自 Python 3.13 起,
_enablelegacywindowsfsencoding()
函式已被棄用。請改用PYTHONLEGACYWINDOWSFSENCODING
環境變數。
-
自 Python 3.14 起,
sysconfig.expand_makefile_vars()
函式已被棄用。請改用sysconfig.get_paths()
的vars
引數。
-
自 Python 3.13 起,未以文件記錄和未被使用的
TarFile.tarfile
屬性已被棄用。
Python 3.17 中待移除的項目¶
-
collections.abc.ByteString
is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)
to test ifobj
implements the buffer protocol at runtime. For use in type annotations, either useBuffer
or a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview
).ByteString
was originally intended to be an abstract class that would serve as a supertype of bothbytes
andbytearray
. However, since the ABC never had any methods, knowing that an object was an instance ofByteString
never actually told you anything useful about the object. Other common buffer types such asmemoryview
were also never understood as subtypes ofByteString
(either at runtime or by static type checkers).See PEP 688 for more details. (Contributed by Shantanu Jain in gh-91896.)
-
在 Python 3.14 之前,舊式聯集是使用私有類別
typing._UnionGenericAlias
實作的。這個類別不再被需要,但為了向後相容性而保留,並計劃將在 Python 3.17 中移除。使用者應該改用文件中記錄的內省輔助函式,例如typing.get_origin()
和typing.get_args()
,或者依賴私有實作細節。typing.ByteString
, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)
to test ifobj
implements the buffer protocol at runtime. For use in type annotations, either useBuffer
or a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview
).ByteString
was originally intended to be an abstract class that would serve as a supertype of bothbytes
andbytearray
. However, since the ABC never had any methods, knowing that an object was an instance ofByteString
never actually told you anything useful about the object. Other common buffer types such asmemoryview
were also never understood as subtypes ofByteString
(either at runtime or by static type checkers).See PEP 688 for more details. (Contributed by Shantanu Jain in gh-91896.)
Python 3.19 中待移除的項目¶
未來版本中的待移除項目¶
以下 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
的嚴格子類別實例。將
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 都將提供一個相容性 shim。(由 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
。
應改用帶有
PyConfig
的Py_InitializeFromConfig()
API。全域配置變數:
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()
)
應改用帶有
PyConfig
的Py_InitializeFromConfig()
API 來設定這些選項。或者也可以使用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 project 來取得這些於 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()
。執行緒局部儲存 (Thread Local Storage, TLS) API: