已棄用項目¶
Python 3.13 中待移除的項目¶
模組(請見 PEP 594):
其他模組:
lib2to3和 2to3 程式 (gh-84540)
API:
configparser.LegacyInterpolation(gh-90765)locale.resetlocale()(gh-90817)turtle.RawTurtle.settiltangle()(gh-50096)unittest.findTestCases()(gh-50096)unittest.getTestCaseNames()(gh-50096)unittest.makeSuite()(gh-50096)unittest.TestProgram.usageExit()(gh-67048)webbrowser.MacOSX(gh-86421)classmethod描述器鏈接 (gh-89519)importlib.resources的已棄用方法:contents()is_resource()open_binary()open_text()path()read_binary()read_text()
請改用
importlib.resources.files()。請參閱 importlib-resources: Migrating from Legacy (gh-106531)
Python 3.14 中待移除的項目¶
argparse:argparse.BooleanOptionalAction的 type、choices 和 metavar 參數已被棄用,將在 3.14 中移除。 (由 Nikita Sobolev 於 gh-92248 貢獻。)ast:自 Python 3.8 起,下列功能已在文件中被棄用,現在在存取或使用時會於 runtime 發出DeprecationWarning,並將在 Python 3.14 中移除:ast.Numast.Strast.Bytesast.NameConstantast.Ellipsis
請改用
ast.Constant。(由 Serhiy Storchaka 於 gh-90953 貢獻。)-
已棄用並將在 Python 3.14 中移除的 child watcher 類別:
MultiLoopChildWatcher、FastChildWatcher、AbstractChildWatcher和SafeChildWatcher。 (由 Kumar Aditya 於 gh-94597 貢獻。)asyncio.set_child_watcher()、asyncio.get_child_watcher()、asyncio.AbstractEventLoopPolicy.set_child_watcher()和asyncio.AbstractEventLoopPolicy.get_child_watcher()已被棄用並將在 Python 3.14 中移除。(由 Kumar Aditya 於 gh-94597 貢獻。)預設事件迴圈策略的
get_event_loop()方法現在會在沒有設定目前事件迴圈且決定建立一個時發出DeprecationWarning。 (由 Serhiy Storchaka 和 Guido van Rossum 於 gh-100160 貢獻。)
collections.abc:已棄用ByteString。請改用Sequence或Buffer。在 typing 中使用時,請改用聯集,如bytes | bytearray,或collections.abc.Buffer。(由 Shantanu Jain 於 gh-91896 貢獻。)email:已棄用email.utils.localtime()中的 isdst 參數。(由 Alan Williams 於 gh-72346 貢獻。)importlib:__package__和__cached__將不再被設定或被 import 系統考慮。 (gh-97879)importlib.abc的已棄用類別:importlib.abc.ResourceReaderimportlib.abc.Traversableimportlib.abc.TraversableResources
請改用
importlib.resources.abc類別:(由 Jason R. Coombs 和 Hugo van Kemenade 貢獻於 gh-93963。)
itertools有不以文件記錄、效率低下、過去常有 bug 且不一致的 copy、deepcopy 和 pickle 操作支援。將在 3.14 中移除以大幅減少程式碼量和維護負擔。 (由 Raymond Hettinger 於 gh-101588 貢獻。)multiprocessing:預設的啟動方法將在 Linux、BSD 和其他非 macOS POSIX 平台上更改為更安全的 方法,目前'fork'是預設值 (gh-84559)。對此增加一個 runtime 警告被認為太過擾人,因為 大多數程式碼不會在意。請使用get_context()或set_start_method()API 來明確指定你的程式碼何時需要'fork'。請參閱 Contexts and start methods。pathlib:已棄用is_relative_to()和relative_to():額外引數的傳遞已被棄用。pkgutil:find_loader()和get_loader()現在會引發DeprecationWarning;請改用importlib.util.find_spec()。 (由 Nikita Sobolev 於 gh-97850 貢獻。)pty:master_open():請用pty.openpty()。slave_open():請用pty.openpty()。
-
execute()和executemany(),如果使用 named placeholders 且 parameters 是序列而不是dict。
typing:自 Python 3.9 起已被棄用的ByteString現在在使用時會發出DeprecationWarning。urllib:urllib.parse.Quoter已被棄用:它並非預期的公開 API。(由 Gregory P. Smith 於 gh-88168 貢獻。)
Python 3.15 中待移除的項目¶
http.server.CGIHTTPRequestHandler將會被移除,連同其相關的--cgi旗標到python -m http.server。它已經過時且很少被使用。沒有直接的替代方案。任何東西都比 CGI 更好的來介接一個帶有請求處理器的網頁伺服器。-
load_module()method:請改用exec_module()。
locale:locale.getdefaultlocale()已在 Python 3.11 中被棄用,原本計劃在 Python 3.13 中移除 (gh-90817),但被延後至 Python 3.15。請改用locale.setlocale()、locale.getencoding()和locale.getlocale()。 (由 Hugo van Kemenade 於 gh-111187 貢獻。)pathlib:pathlib.PurePath.is_reserved()已被棄用並計劃在 Python 3.15 中移除。從 Python 3.13 開始,請用os.path.isreserved來偵測 Windows 上的保留路徑。platform:java_ver()已被棄用並將在 3.15 中移除。它幾乎沒有被測試過,API 令人困惑並且只對 Jython 支援有用。 (由 Nikita Sobolev 於 gh-116349 貢獻。)-
The check_home argument of
sysconfig.is_python_build()has been deprecated since Python 3.12.
threading:對threading.RLock()傳遞任何引數現在已被棄用。C 版本允許任意數量的引數和關鍵字引數,但它們會被忽略。Python 版本不允許任何引數。所有引數將在 Python 3.15 中從threading.RLock()中移除。 (由 Nikita Sobolev 於 gh-102029 貢獻。)-
用於建立
NamedTuple類別的未以文件記錄之關鍵字引數語法 (NT = NamedTuple("NT", x=int)) 已棄用,並將在 3.15 中被禁止。請改用基於類別的語法或函式語法 (functional syntax)。
-
types.CodeType: Accessingco_lnotabwas deprecated in PEP 626 since 3.10 and was planned to be removed in 3.12, but it only got a properDeprecationWarningin 3.12. May be removed in 3.15. (Contributed by Nikita Sobolev in gh-101866.)
-
當使用函式語法來建立
NamedTuple類別時,沒將值傳遞給 fields 參數的方式 (NT = NamedTuple("NT")) 已被棄用,將None傳遞給 fields 參數(NT = NamedTuple("NT", None))也已被棄用。這兩者將在 Python 3.15 中會被禁止。要建立一個沒有欄位的NamedTuple類別,請使用class NT(NamedTuple): pass或NT = NamedTuple("NT", [])。
typing.TypedDict:當使用函式語法來建立TypedDict類別時,沒將值傳遞給 fields 參數的方式(TD = TypedDict("TD"))已被棄用,將None傳遞給 fields 參數(TD = TypedDict("TD", None))也已被棄用。這兩者將在 Python 3.15 中會被禁止。要建立一個沒有欄位的TypedDict類別,請使用class TD(TypedDict): pass或TD = TypedDict("TD", {})。wave:已棄用wave.Wave_read和wave.Wave_write類別的getmark()、setmark()和getmarkers()方法。它們將在 Python 3.15 中被移除。 (由 Victor Stinner 於 gh-105096 貢獻。)
Python 3.16 中待移除的項目¶
The import system:
Setting
__loader__on a module while failing to set__spec__.loaderis deprecated. In Python 3.16,__loader__will cease to be set or taken into consideration by the import system or the standard library.
array:array.array'u'型別 (wchar_t):請改用'w'型別 (Py_UCS4)。builtins:~bool,對 bool 進行位元反轉。symtable:由於並沒有太多關注,已棄用symtable.Class.get_methods()。 (由 Bénédikt Tran 於 gh-119698 貢獻。)
未來版本中的待移除項目¶
以下 API 將在未來被移除,雖然目前尚未安排移除日期。
argparse:已棄用巢狀引數群組和巢狀互斥群組。-
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 貢獻。)-
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_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()。
unittest.IsolatedAsyncioTestCase:從測試案例中回傳非None的值已被棄用。urllib.parse已棄用函式:請改用urlparse()。splitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
urllib.request:呼叫請求的URLopener和FancyURLopener風格已被棄用。請改用更新的urlopen()函式和方法。wsgiref:SimpleHandler.stdout.write()不應該進行部分寫入。xml.etree.ElementTree:已棄用對Element的真值測試。在未來版本中,它將始終回傳True。請改用明確的len(elem)或elem is not None測試。
C API 的棄用項目¶
Python 3.14 中待移除的項目¶
PyDictObject中的ma_version_tag欄位,用於擴充模組 (PEP 699;gh-101193)。設定 Python 初始化的函式,Python 3.11 中已被棄用:
PySys_SetArgvEx(): SetPyConfig.argvinstead.PySys_SetArgv(): SetPyConfig.argvinstead.Py_SetProgramName(): SetPyConfig.program_nameinstead.Py_SetPythonHome(): SetPyConfig.homeinstead.
Py_InitializeFromConfig()API 應該與PyConfig一起使用。全域設定變數:
Py_DebugFlag: UsePyConfig.parser_debuginstead.Py_VerboseFlag: UsePyConfig.verboseinstead.Py_QuietFlag: UsePyConfig.quietinstead.Py_InteractiveFlag: UsePyConfig.interactiveinstead.Py_InspectFlag: UsePyConfig.inspectinstead.Py_OptimizeFlag: UsePyConfig.optimization_levelinstead.Py_NoSiteFlag: UsePyConfig.site_importinstead.Py_BytesWarningFlag: UsePyConfig.bytes_warninginstead.Py_FrozenFlag: UsePyConfig.pathconfig_warningsinstead.Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentinstead.Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeinstead.Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryinstead.Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioinstead.Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedinstead.Py_IsolatedFlag: UsePyConfig.isolatedinstead.Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodinginstead.Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioinstead.Py_FileSystemDefaultEncoding: UsePyConfig.filesystem_encodinginstead.Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodinginstead.Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsinstead.Py_UTF8Mode: UsePyPreConfig.utf8_modeinstead. (seePy_PreInitialize())
Py_InitializeFromConfig()API 應該與PyConfig一起使用。
Python 3.15 中待移除的項目¶
libmpdecimal的打包副本 (bundled copy)。The
PyImport_ImportModuleNoBlock(): UsePyImport_ImportModule()instead.PyWeakref_GetObject()andPyWeakref_GET_OBJECT(): UsePyWeakref_GetRef()instead.Py_UNICODEtype and thePy_UNICODE_WIDEmacro: Usewchar_tinstead.Python 初始化函式:
PySys_ResetWarnOptions(): Clearsys.warnoptionsandwarnings.filtersinstead.Py_GetExecPrefix(): Getsys.exec_prefixinstead.Py_GetPath(): Getsys.pathinstead.Py_GetPrefix(): Getsys.prefixinstead.Py_GetProgramFullPath(): Getsys.executableinstead.Py_GetProgramName(): Getsys.executableinstead.Py_GetPythonHome(): GetPyConfig.homeor thePYTHONHOMEenvironment variable instead.
未來版本中的待移除項目¶
下列 API 已被棄用並將會被移除,不過目前尚未訂定移除日期。
Py_TPFLAGS_HAVE_FINALIZE: Unneeded since Python 3.8.PyErr_Fetch(): UsePyErr_GetRaisedException()instead.PyErr_NormalizeException(): UsePyErr_GetRaisedException()instead.PyErr_Restore(): UsePyErr_SetRaisedException()instead.PyModule_GetFilename(): UsePyModule_GetFilenameObject()instead.PyOS_AfterFork(): UsePyOS_AfterFork_Child()instead.PySlice_GetIndicesEx(): UsePySlice_Unpack()andPySlice_AdjustIndices()instead.PyUnicode_AsDecodedObject(): UsePyCodec_Decode()instead.PyUnicode_AsDecodedUnicode(): UsePyCodec_Decode()instead.PyUnicode_AsEncodedObject(): UsePyCodec_Encode()instead.PyUnicode_AsEncodedUnicode(): UsePyCodec_Encode()instead.PyUnicode_READY(): Unneeded since Python 3.12PyErr_Display(): UsePyErr_DisplayException()instead._PyErr_ChainExceptions(): Use_PyErr_ChainExceptions1()instead.PyBytesObject.ob_shash成員:請改為呼叫PyObject_Hash()。PyDictObject.ma_version_tag成員。執行緒局部儲存 (Thread Local Storage, TLS) API:
PyThread_create_key(): UsePyThread_tss_alloc()instead.PyThread_delete_key(): UsePyThread_tss_free()instead.PyThread_set_key_value(): UsePyThread_tss_set()instead.PyThread_get_key_value(): UsePyThread_tss_get()instead.PyThread_delete_key_value(): UsePyThread_tss_delete()instead.PyThread_ReInitTLS(): Unneeded since Python 3.7.