Desusos¶
Pending removal in Python 3.15¶
The import system:
Setting
__cached__on a module while failing to set__spec__.cachedis deprecated. In Python 3.15,__cached__will cease to be set or take into consideration by the import system or standard library. (gh-97879)Setting
__package__on a module while failing to set__spec__.parentis deprecated. In Python 3.15,__package__will cease to be set or take into consideration by the import system or standard library. (gh-97879)
-
La función
ctypes.SetPointerType()no documentada ha quedado obsoleta desde Python 3.13.
-
El obsoleto y poco utilizado
CGIHTTPRequestHandlerha quedado obsoleto desde Python 3.13. No existe un reemplazo directo. Anything es mejor que CGI para interconectar un servidor web con un controlador de solicitudes.La bandera
--cgide la interfaz de línea de comandos python -m http.server ha quedado obsoleta desde Python 3.13.
-
Método
load_module(): utiliceexec_module()en su lugar.
-
La función
getdefaultlocale()ha quedado obsoleta desde Python 3.11. Su eliminación se había planeado originalmente para Python 3.13 (gh-90817), pero se pospuso hasta Python 3.15. Utilicegetlocale(),setlocale()ygetencoding()en su lugar. (Contribuido por Hugo van Kemenade en gh-111187.)
-
PurePath.is_reserved()ha quedado obsoleto desde Python 3.13. Utiliceos.path.isreserved()para detectar rutas reservadas en Windows.
-
java_ver()ha quedado obsoleto desde Python 3.13. Esta función solo es útil para la compatibilidad con Jython, tiene una API confusa y, en gran medida, no se ha probado.
-
The check_home argument of
sysconfig.is_python_build()has been deprecated since Python 3.12.
-
RLock()no acepta argumentos en Python 3.15. El paso de cualquier argumento ha quedado obsoleto desde Python 3.14, ya que la versión de Python no permite ningún argumento, pero la versión de C permite cualquier cantidad de argumentos posicionales o de palabras clave, ignorando todos los argumentos.
-
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.)
-
The undocumented keyword argument syntax for creating
NamedTupleclasses (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.When using the functional syntax of
TypedDicts, failing to pass a value to the fields parameter (TD = TypedDict("TD")) or passingNone(TD = TypedDict("TD", None)) has been deprecated since Python 3.13. Useclass TD(TypedDict): passorTD = TypedDict("TD", {})to create a TypedDict with zero field.La función decoradora
typing.no_type_check_decorator()ha quedado obsoleta desde Python 3.13. Después de ocho años en el módulotyping, todavía no ha sido compatible con ningún verificador de tipos importante.
wave:Los métodos
getmark(),setmark()ygetmarkers()de las clasesWave_readyWave_writehan quedado obsoletos desde Python 3.13.
-
load_module()has been deprecated since Python 3.10. Useexec_module()instead. (Contributed by Jiahao Li in gh-125746.)
Pending removal in 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.
-
El código de formato
'u'(wchar_t) ha quedado obsoleto en la documentación desde Python 3.3 y en el entorno de ejecución desde Python 3.13. Utilice el código de formato'w'(Py_UCS4) para caracteres 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.)asynciopolicy 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.Runnerwith loop_factory to use the desired event loop implementation.For example, to use
asyncio.SelectorEventLoopon Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(Contributed by Kumar Aditya in gh-127949.)
-
La inversión bit a bit en tipos booleanos,
~Trueo~False, ha quedado obsoleta desde Python 3.12, ya que produce resultados sorprendentes y poco intuitivos (-2y-1). En su lugar, utilicenot xpara la negación lógica de un valor booleano. En el caso poco frecuente de que necesite la inversión bit a bit del entero subyacente, convierta aintexplícitamente (~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 aValueErrorin Python 3.16. (Contributed by Hugo van Kemenade in gh-75223.)
-
La excepción
ExecErrorha quedado obsoleta desde Python 3.14. No ha sido utilizada por ninguna función enshutildesde Python 3.4 y ahora es un alias deRuntimeError.
-
El método
Class.get_methodsha quedado obsoleto desde Python 3.14.
sys:La función
_enablelegacywindowsfsencoding()ha quedado obsoleta desde Python 3.13. En su lugar, utilice la variable de entornoPYTHONLEGACYWINDOWSFSENCODING.
-
The
sysconfig.expand_makefile_vars()function has been deprecated since Python 3.14. Use thevarsargument ofsysconfig.get_paths()instead.
-
El atributo
TarFile.tarfile, no documentado ni utilizado, ha quedado obsoleto desde Python 3.13.
Pending removal in Python 3.17¶
-
collections.abc.ByteStringis scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements the buffer protocol at runtime. For use in type annotations, either useBufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance ofByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere 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.)
-
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.typing.ByteString, deprecated since Python 3.9, is scheduled for removal in Python 3.17.Use
isinstance(obj, collections.abc.Buffer)to test ifobjimplements the buffer protocol at runtime. For use in type annotations, either useBufferor a union that explicitly specifies the types your code supports (e.g.,bytes | bytearray | memoryview).ByteStringwas originally intended to be an abstract class that would serve as a supertype of bothbytesandbytearray. However, since the ABC never had any methods, knowing that an object was an instance ofByteStringnever actually told you anything useful about the object. Other common buffer types such asmemoryviewwere 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.)
Pending removal in Python 3.19¶
Pending removal in future versions¶
Las siguientes API se eliminarán en el futuro, aunque actualmente no hay una fecha programada para su eliminación.
-
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.FileTypetype converter is deprecated.
-
Generadores: las firmas
throw(type, exc, tb)yathrow(type, exc, tb)están obsoletas: utilicethrow(exc)yathrow(exc)en su lugar, la firma de argumento único.Actualmente, Python acepta literales numéricos seguidos inmediatamente de palabras clave, por ejemplo,
0in x,1or x,0if 1else 2. Permite expresiones confusas y ambiguas como[0x1for x in y](que se puede interpretar como[0x1 for x in y]o[0x1f or x in y]). Se genera una advertencia de sintaxis si el literal numérico va seguido inmediatamente de una de las palabras claveand,else,for,if,in,isyor. En una versión futura, se cambiará a un error de sintaxis. (gh-87999)Compatibilidad con los métodos
__index__()y__int__()que devuelven un tipo que no es int: estos métodos serán necesarios para devolver una instancia de una subclase estricta deint.Compatibilidad con el método
__float__()que devuelve una subclase estricta defloat: estos métodos serán necesarios para devolver una instancia defloat.Compatibilidad con el método
__complex__()que devuelve una subclase estricta decomplex: estos métodos serán necesarios para devolver una instancia decomplex.Delegación del método
int()al__trunc__().Ahora está obsoleto el paso de un número complejo como argumento real o imag en el constructor
complex(); solo debe pasarse como un único argumento posicional. (Contribuido por Serhiy Storchaka en gh-109218.)
calendar: Las constantescalendar.Januaryycalendar.Februaryhan quedado obsoletas y han sido reemplazadas porcalendar.JANUARYycalendar.FEBRUARY. (Contribuido por Prince Roshan en gh-103636.)codecs: useopen()instead ofcodecs.open(). (gh-133038)codeobject.co_lnotab: utilice el métodocodeobject.co_lines()en su lugar.-
utcnow(): utilicedatetime.datetime.now(tz=datetime.UTC).utcfromtimestamp(): utilicedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: El valor plural debe ser un número entero.-
cache_from_source()El parámetro debug_override está obsoleto: utilice el parámetro optimization en su lugar.
-
Interfaz de tupla
EntryPoints.Noneimplícito en los valores de retorno.
logging: el métodowarn()ha quedado obsoleto desde Python 3.3, utilicewarning()en su lugar.mailbox: El uso del modo de entrada y texto StringIO está obsoleto; en su lugar, utilice BytesIO y el modo binario.os: Llamada aos.register_at_fork()en un proceso multiproceso.pydoc.ErrorDuringImport: Un valor de tupla para el parámetro exc_info está obsoleto, utilice una instancia de excepción.re: Ahora se aplican reglas más estrictas para las referencias numéricas de grupos y los nombres de grupos en expresiones regulares. Ahora solo se aceptan secuencias de dígitos ASCII como referencia numérica. El nombre de grupo en patrones de bytes y cadenas de reemplazo ahora solo puede contener letras y dígitos ASCII y guiones bajos. (Contribuido por Serhiy Storchaka en gh-91760.)Módulos
sre_compile,sre_constantsysre_parse.shutil: El parámetro onerror dermtree()está obsoleto en Python 3.12; utilice el parámetro onexc en su lugar.Opciones y protocolos
ssl:ssl.SSLContextsin argumento de protocolo está obsoleto.ssl.SSLContext:set_npn_protocols()yselected_npn_protocol()están obsoletos: utilice ALPN en su lugar.Opciones de
ssl.OP_NO_SSL*Opciones de
ssl.OP_NO_TLS*ssl.PROTOCOL_SSLv3ssl.PROTOCOL_TLSssl.PROTOCOL_TLSv1ssl.PROTOCOL_TLSv1_1ssl.PROTOCOL_TLSv1_2ssl.TLSVersion.SSLv3ssl.TLSVersion.TLSv1ssl.TLSVersion.TLSv1_1
Métodos
threading:threading.Condition.notifyAll(): utilicenotify_all().threading.Event.isSet(): utiliceis_set().threading.Thread.isDaemon(),threading.Thread.setDaemon(): utilice el atributothreading.Thread.daemon.threading.Thread.getName(),threading.Thread.setName(): utilice el atributothreading.Thread.name.threading.currentThread(): utilicethreading.current_thread().threading.activeCount(): utilicethreading.active_count().
The internal class
typing._UnionGenericAliasis 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: está obsoleto devolver un valor que no seaNonede un caso de prueba.Funciones obsoletas de
urllib.parse:urlparse()en su lugarsplitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()no debería realizar escrituras parciales.xml.etree.ElementTree: La prueba del valor de verdad de unElementestá obsoleta. En una versión futura, siempre devolveráTrue. En su lugar, es preferible realizar pruebas explícitaslen(elem)oelem is not None.sys._clear_type_cache()is deprecated: usesys._clear_internal_caches()instead.
C API deprecations¶
Pending removal in Python 3.15¶
PyImport_ImportModuleNoBlock(): utilicePyImport_ImportModule()en su lugar.PyWeakref_GetObject()andPyWeakref_GET_OBJECT(): UsePyWeakref_GetRef()instead. The pythoncapi-compat project can be used to getPyWeakref_GetRef()on Python 3.12 and older.Tipo
Py_UNICODEy macroPy_UNICODE_WIDE: utilicewchar_ten su lugar.PyUnicode_AsDecodedObject(): UtilicePyCodec_Decode()en su lugar.PyUnicode_AsDecodedUnicode(): UsePyCodec_Decode()instead; Note that some codecs (for example, «base64») may return a type other thanstr, such asbytes.PyUnicode_AsEncodedObject(): UtilicePyCodec_Encode()en su lugar.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 thePYTHONHOMEenvironment variable instead.
The pythoncapi-compat project can be used to get
PyConfig_Get()on Python 3.13 and older.Funciones para configurar la inicialización de Python, obsoletas en Python 3.11:
PySys_SetArgvEx(): EstablezcaPyConfig.argven su lugar.PySys_SetArgv(): EstablezcaPyConfig.argven su lugar.Py_SetProgramName(): EstablezcaPyConfig.program_nameen su lugar.Py_SetPythonHome(): EstablezcaPyConfig.homeen su lugar.PySys_ResetWarnOptions(): borresys.warnoptionsywarnings.filtersen su lugar.
La API
Py_InitializeFromConfig()debe utilizarse conPyConfig.Variables de configuración global:
Py_DebugFlag: UsePyConfig.parser_debugorPyConfig_Get("parser_debug")instead.Py_VerboseFlag: UsePyConfig.verboseorPyConfig_Get("verbose")instead.Py_QuietFlag: UsePyConfig.quietorPyConfig_Get("quiet")instead.Py_InteractiveFlag: UsePyConfig.interactiveorPyConfig_Get("interactive")instead.Py_InspectFlag: UsePyConfig.inspectorPyConfig_Get("inspect")instead.Py_OptimizeFlag: UsePyConfig.optimization_levelorPyConfig_Get("optimization_level")instead.Py_NoSiteFlag: UsePyConfig.site_importorPyConfig_Get("site_import")instead.Py_BytesWarningFlag: UsePyConfig.bytes_warningorPyConfig_Get("bytes_warning")instead.Py_FrozenFlag: UsePyConfig.pathconfig_warningsorPyConfig_Get("pathconfig_warnings")instead.Py_IgnoreEnvironmentFlag: UsePyConfig.use_environmentorPyConfig_Get("use_environment")instead.Py_DontWriteBytecodeFlag: UsePyConfig.write_bytecodeorPyConfig_Get("write_bytecode")instead.Py_NoUserSiteDirectory: UsePyConfig.user_site_directoryorPyConfig_Get("user_site_directory")instead.Py_UnbufferedStdioFlag: UsePyConfig.buffered_stdioorPyConfig_Get("buffered_stdio")instead.Py_HashRandomizationFlag: UsePyConfig.use_hash_seedandPyConfig.hash_seedorPyConfig_Get("hash_seed")instead.Py_IsolatedFlag: UsePyConfig.isolatedorPyConfig_Get("isolated")instead.Py_LegacyWindowsFSEncodingFlag: UsePyPreConfig.legacy_windows_fs_encodingorPyConfig_Get("legacy_windows_fs_encoding")instead.Py_LegacyWindowsStdioFlag: UsePyConfig.legacy_windows_stdioorPyConfig_Get("legacy_windows_stdio")instead.Py_FileSystemDefaultEncoding,Py_HasFileSystemDefaultEncoding: UsePyConfig.filesystem_encodingorPyConfig_Get("filesystem_encoding")instead.Py_FileSystemDefaultEncodeErrors: UsePyConfig.filesystem_errorsorPyConfig_Get("filesystem_errors")instead.Py_UTF8Mode: UsePyPreConfig.utf8_modeorPyConfig_Get("utf8_mode")instead. (seePy_PreInitialize())
The
Py_InitializeFromConfig()API should be used withPyConfigto set these options. OrPyConfig_Get()can be used to get these options at runtime.
Pending removal in Python 3.18¶
The following private functions are deprecated and planned for removal in Python 3.18:
_PyBytes_Join(): usePyBytes_Join()._PyDict_GetItemStringWithError(): usePyDict_GetItemStringRef()._PyDict_Pop(): usePyDict_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_WriteASCII(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. (Contributed by Victor Stinner in gh-128863.)
Pending removal in future versions¶
Las siguientes API están obsoletas y se eliminarán, aunque actualmente no hay una fecha programada para su eliminación.
Py_TPFLAGS_HAVE_FINALIZE: Innecesario desde Python 3.8.PyErr_Fetch(): UtilicePyErr_GetRaisedException()en su lugar.PyErr_NormalizeException(): UtilicePyErr_GetRaisedException()en su lugar.PyErr_Restore(): UtilicePyErr_SetRaisedException()en su lugar.PyModule_GetFilename(): UtilicePyModule_GetFilenameObject()en su lugar.PyOS_AfterFork(): UtilicePyOS_AfterFork_Child()en su lugar.PySlice_GetIndicesEx(): UtilicePySlice_Unpack()yPySlice_AdjustIndices()en su lugar.PyUnicode_READY(): Innecesario desde Python 3.12PyErr_Display(): UtilicePyErr_DisplayException()en su lugar._PyErr_ChainExceptions(): Utilice_PyErr_ChainExceptions1()en su lugar.Miembro de
PyBytesObject.ob_shash: llame aPyObject_Hash()en su lugar.API de almacenamiento local de subprocesos (TLS):
PyThread_create_key(): UtilicePyThread_tss_alloc()en su lugar.PyThread_delete_key(): UtilicePyThread_tss_free()en su lugar.PyThread_set_key_value(): UtilicePyThread_tss_set()en su lugar.PyThread_get_key_value(): UtilicePyThread_tss_get()en su lugar.PyThread_delete_key_value(): UtilicePyThread_tss_delete()en su lugar.PyThread_ReInitTLS(): Innecesario desde Python 3.7.