Desusos

Pending removal in Python 3.16

  • The import system:

    • Setting __loader__ on a module while failing to set __spec__.loader is deprecated. In Python 3.16, __loader__ will cease to be set or taken into consideration by the import system or the standard library.

    • Setting __package__ on a module while failing to set __spec__.parent is deprecated. In Python 3.16, __package__ will cease to be taken into consideration by the import system or standard library. (gh-97879)

  • The bundled copy of libmpdec.

  • array:

    • 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:

  • builtins:

    • La inversión bit a bit en tipos booleanos, ~True o ~False, ha quedado obsoleta desde Python 3.12, ya que produce resultados sorprendentes y poco intuitivos (-2 y -1). En su lugar, utilice not x para 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 a int explícitamente (~int(x)).

  • functools:

    • Calling the Python implementation of functools.reduce() with function or sequence as keyword arguments has been deprecated since Python 3.14.

  • logging:

    • 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.)

  • mimetypes:

  • shutil:

    • La excepción ExecError ha quedado obsoleta desde Python 3.14. No ha sido utilizada por ninguna función en shutil desde Python 3.4 y ahora es un alias de RuntimeError.

  • symtable:

    • The symtable.Class.get_methods() method has been deprecated since Python 3.14.

  • sys:

    • The _enablelegacywindowsfsencoding() function has been deprecated since Python 3.13. Use the PYTHONLEGACYWINDOWSFSENCODING environment variable instead.

  • sysconfig:

    • The sysconfig.expand_makefile_vars() function has been deprecated since Python 3.14. Use the vars argument of sysconfig.get_paths() instead.

  • tarfile:

    • The undocumented and unused TarInfo.tarfile attribute has been deprecated since Python 3.13.

Pending removal in Python 3.17

  • datetime:

    • strptime() calls using a format string containing %e (day of month) without a year. This has been deprecated since Python 3.15. (Contributed by Stan Ulbrych in gh-70647.)

  • collections.abc:

    • collections.abc.ByteString is scheduled for removal in Python 3.17.

      Use isinstance(obj, collections.abc.Buffer) to test if obj implements the buffer protocol at runtime. For use in type annotations, either use Buffer 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 both bytes and bytearray. However, since the ABC never had any methods, knowing that an object was an instance of ByteString never actually told you anything useful about the object. Other common buffer types such as memoryview were also never understood as subtypes of ByteString (either at runtime or by static type checkers).

      See PEP 688 for more details. (Contributed by Shantanu Jain in gh-91896.)

  • encodings:

  • webbrowser:

    • webbrowser.MacOSXOSAScript is deprecated in favour of webbrowser.MacOS. (gh-137586)

  • typing:

    • 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 like typing.get_origin() and typing.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 if obj implements the buffer protocol at runtime. For use in type annotations, either use Buffer 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 both bytes and bytearray. However, since the ABC never had any methods, knowing that an object was an instance of ByteString never actually told you anything useful about the object. Other common buffer types such as memoryview were also never understood as subtypes of ByteString (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.18

  • No longer accept a boolean value when a file descriptor is expected. (Contributed by Serhiy Storchaka in gh-82626.)

  • decimal:

    • The non-standard and undocumented Decimal format specifier 'N', which is only supported in the decimal module’s C implementation, has been deprecated since Python 3.13. (Contributed by Serhiy Storchaka in gh-89902.)

  • Deprecations defined by PEP 829:

    • import lines in name.pth files are silently ignored.

    (Contributed by Barry Warsaw in gh-148641.)

Pending removal in Python 3.19

  • ctypes:

    • Implicitly switching to the MSVC-compatible struct layout by setting _pack_ but not _layout_ on non-Windows platforms.

  • hashlib:

    • In hash function constructors such as new() or the direct hash-named constructors such as md5() and sha256(), their optional initial data parameter could also be passed a keyword argument named data= or string= in various hashlib 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.

  • http.cookies:

  • imaplib:

    • Altering IMAP4.file is now deprecated and slated for removal in Python 3.19. This property is now unused and changing its value does not automatically close the current file.

      Before Python 3.14, this property was used to implement the corresponding read() and readline() methods for IMAP4 but this is no longer the case since then.

Pending removal in Python 3.20

Pending removal in Python 3.21

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.

  • argparse:

    • 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.

  • builtins:

    • Generadores: las firmas throw(type, exc, tb) y athrow(type, exc, tb) están obsoletas: utilice throw(exc) y athrow(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 clave and, else, for, if, in, is y or. 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 de int.

    • Compatibilidad con el método __float__() que devuelve una subclase estricta de float: estos métodos serán necesarios para devolver una instancia de float.

    • Compatibilidad con el método __complex__() que devuelve una subclase estricta de complex: estos métodos serán necesarios para devolver una instancia de complex.

    • 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 constantes calendar.January y calendar.February han quedado obsoletas y han sido reemplazadas por calendar.JANUARY y calendar.FEBRUARY. (Contribuido por Prince Roshan en gh-103636.)

  • codecs: use open() instead of codecs.open(). (gh-133038)

  • codeobject.co_lnotab: use the codeobject.co_lines() method instead.

  • datetime:

    • utcnow(): utilice datetime.datetime.now(tz=datetime.UTC).

    • utcfromtimestamp(): utilice datetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).

  • gettext: El valor plural debe ser un número entero.

  • importlib:

    • cache_from_source() El parámetro debug_override está obsoleto: utilice el parámetro optimization en su lugar.

  • importlib.metadata:

    • Interfaz de tupla EntryPoints.

    • None implícito en los valores de retorno.

  • logging: el método warn() ha quedado obsoleto desde Python 3.3, utilice warning() 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: Calling os.register_at_fork() in a multi-threaded process.

  • os.path: os.path.commonprefix() is deprecated, use os.path.commonpath() for path prefixes. The os.path.commonprefix() function is being deprecated due to having a misleading name and module. The function is not safe to use for path prefixes despite being included in a module about path manipulation, meaning it is easy to accidentally introduce path traversal vulnerabilities into Python programs by using this function.

  • 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.)

  • shutil: El parámetro onerror de rmtree() está obsoleto en Python 3.12; utilice el parámetro onexc en su lugar.

  • Opciones y protocolos ssl:

    • ssl.SSLContext sin argumento de protocolo está obsoleto.

    • ssl.SSLContext: set_npn_protocols() y selected_npn_protocol() están obsoletos: utilice ALPN en su lugar.

    • Opciones de ssl.OP_NO_SSL*

    • Opciones de 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

  • Métodos threading:

  • typing.Text (gh-92332).

  • The internal class typing._UnionGenericAlias is no longer used to implement typing.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 sea None de un caso de prueba.

  • Funciones obsoletas de urllib.parse: urlparse() en su lugar

    • splitattr()

    • 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 un Element está obsoleta. En una versión futura, siempre devolverá True. En su lugar, es preferible realizar pruebas explícitas len(elem) o elem is not None.

  • sys._clear_type_cache() is deprecated: use sys._clear_internal_caches() instead.

Soft deprecations

There are no plans to remove soft deprecated APIs.

  • re.match() and re.Pattern.match() are now soft deprecated in favor of the new re.prefixmatch() and re.Pattern.prefixmatch() APIs, which have been added as alternate, more explicit names. These are intended to be used to alleviate confusion around what match means by following the Zen of Python’s «Explicit is better than implicit» mantra. Most other language regular expression libraries use an API named match to mean what Python has always called search.

    We do not plan to remove the older match() name, as it has been used in code for over 30 years. Code supporting older versions of Python should continue to use match(), while new code should prefer prefixmatch(). See prefixmatch() vs. match().

    (Contributed by Gregory P. Smith in gh-86519 and Hugo van Kemenade in gh-148100.)

C API deprecations

Pending removal in Python 3.16

Pending removal in Python 3.18

Pending removal in Python 3.19

  • PEP 456 embedders support for the string hashing scheme definition.

Pending removal in Python 3.20

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.