Descontinuações¶
Remoção pendente no Python 3.17¶
-
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.ByteStringestá agendado para remoção no Python 3.17.Use
isinstance(obj, collections.abc.Buffer)para testar seobjimplementa o protocolo de buffer em tempo de execução. Para uso em anotações de tipo, useBufferou uma união que especifique explicitamente os tipos suportados pelo seu código (por exemplo,bytes | bytearray | memoryview).ByteStringfoi originalmente concebido para ser uma classe abstrata que serviria como um supertipo debytesebytearray. No entanto, como o ABC nunca teve métodos, saber que um objeto era uma instância deByteStringnunca lhe dizia nada de útil sobre o objeto. Outros tipos comuns de buffer, comomemoryview, também nunca foram entendidos como subtipos deByteString(seja em tempo de execução ou por verificadores de tipo estáticos).Veja PEP 688 para mais detalhes. (Contribuição de Shantanu Jain em gh-91896.)
-
Passing non-ascii encoding names to
encodings.normalize_encoding()is deprecated and scheduled for removal in Python 3.17. (Contributed by Stan Ulbrych in gh-136702.)
-
webbrowser.MacOSXOSAScriptis deprecated in favour ofwebbrowser.MacOS. (gh-137586)
-
Antes do Python 3.14, as uniões antigas eram implementadas usando a classe privada
typing._UnionGenericAlias. Essa classe não é mais necessária para a implementação, mas foi mantida para compatibilidade com versões anteriores, com remoção prevista para o Python 3.17. Os usuários devem usar auxiliares de introspecção documentados, comotyping.get_origin()etyping.get_args(), em vez de depender de detalhes de implementação privada.typing.ByteString, obsoleto desde o Python 3.9, está programado para ser removido no Python 3.17.Use
isinstance(obj, collections.abc.Buffer)para testar seobjimplementa o protocolo de buffer em tempo de execução. Para uso em anotações de tipo, useBufferou uma união que especifique explicitamente os tipos suportados pelo seu código (por exemplo,bytes | bytearray | memoryview).ByteStringfoi originalmente concebido para ser uma classe abstrata que serviria como um supertipo debytesebytearray. No entanto, como o ABC nunca teve métodos, saber que um objeto era uma instância deByteStringnunca lhe dizia nada de útil sobre o objeto. Outros tipos comuns de buffer, comomemoryview, também nunca foram entendidos como subtipos deByteString(seja em tempo de execução ou por verificadores de tipo estáticos).Veja PEP 688 para mais detalhes. (Contribuição de Shantanu Jain em gh-91896.)
-
The
tkinter.Variablemethodstrace_variable(),trace()(an alias oftrace_variable()),trace_vdelete()andtrace_vinfo(), deprecated since Python 3.14, are scheduled for removal in Python 3.17. Usetrace_add(),trace_remove()andtrace_info()instead. (Contributed by Serhiy Storchaka in gh-120220.)
Remoção pendente no Python 3.18¶
Remoção pendente no Python 3.19¶
-
In hash function constructors such as
new()or the direct hash-named constructors such asmd5()andsha256(), their optional initial data parameter could also be passed a keyword argument nameddata=orstring=in varioushashlibimplementations.Support for the
stringkeyword argument name is now deprecated and slated for removal in Python 3.19.Before Python 3.13, the
stringkeyword 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.Morsel.js_output()is deprecated and will be removed in Python 3.19.http.cookies.BaseCookie.js_output()is deprecated and will be removed in Python 3.19.
-
Altering
IMAP4.fileis 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()andreadline()methods forIMAP4but this is no longer the case since then.
Remoção pendente no Python 3.20¶
Calling the
__new__()method ofstruct.Structwithout the format argument is deprecated and will be removed in Python 3.20. Calling__init__()method on initializedStructobjects is deprecated and will be removed in Python 3.20.(Contributed by Sergey B Kirpichev and Serhiy Storchaka in gh-143715.)
The
__version__,versionandVERSIONattributes have been deprecated in these standard library modules and will be removed in Python 3.20. Usesys.version_infoinstead.ctypes.macholibdecimal(usedecimal.SPEC_VERSIONinstead)logging(__date__also deprecated)xml.sax.expatreader
(Contributed by Hugo van Kemenade and Stan Ulbrych in gh-76007.)
Deprecations defined by PEP 829:
Warnings are produced for
importlines found inname.pthfiles.name.pthfiles are no longer decoded in the locale encoding by default. They MUST be encoded inutf-8-sig.
(Contributed by Barry Warsaw in gh-148641.)
ast:Creating instances of abstract AST nodes (such as
ast.ASTorast.expr) is deprecated and will raise an error in Python 3.20.
Pending removal in Python 3.21¶
-
Soft-deprecated since Python 3.3
abc.abstractclassmethod,abc.abstractstaticmethod, andabc.abstractpropertynow raise aDeprecationWarning. These classes will be removed in Python 3.21, instead useabc.abstractmethod()withclassmethod(),staticmethod(), andpropertyrespectively.
ast:Classes
slice,Index,ExtSlice,Suite,Param,AugLoadandAugStore, will be removed in Python 3.21. These types are not generated by the parser or accepted by the code generator.The
dimsproperty ofast.Tuplewill be removed in Python 3.21. Use theast.Tuple.eltsproperty instead.
Remoção pendente em versões futuras¶
As APIs a seguir serão removidas no futuro, embora atualmente não haja uma data agendada para sua remoção.
-
O aninhamento de grupos de argumentos e o aninhamento de grupos mutuamente exclusivos estão descontinuado.
A passagem do argumento nomeado não documentado prefix_chars para
add_argument_group()agora está descontinuado.O conversor de tipo
argparse.FileTypeestá descontinuado.
-
Geradores: a assinatura
throw(type, exc, tb)eathrow(type, exc, tb)está descontinuada: usethrow(exc)eathrow(exc), a assinatura do argumento único.Atualmente Python aceita literais numéricos imediatamente seguidos por palavras reservadas como, por exemplo,
0in x,1or x,0if 1else 2. Ele permite expressões confusas e ambíguas como[0x1for x in y](que pode ser interpretada como[0x1 for x in y]ou[0x1f or x in y]). Um aviso de sintaxe é levantado se o literal numérico for imediatamente seguido por uma das palavras reservadasand,else,for,if,in,iseor. Em uma versão futura, será alterado para um erro de sintaxe. (gh-87999)Suporte para métodos
__index__()e__int__()retornando tipo não-int: esses métodos serão necessários para retornar uma instância de uma subclasse estrita deint.Suporte para o método
__float__()retornando uma subclasse estrita defloat: esses métodos serão necessários para retornar uma instância defloat.Suporte para o método
__complex__()retornando uma subclasse estrita decomplex: esses métodos serão necessários para retornar uma instância decomplex.Passar um número complexo como argumento real ou imag no construtor
complex()agora está descontinuado; deve ser passado apenas como um único argumento posicional. (Contribuição de Serhiy Storchaka em gh-109218.)
calendar: as constantescalendar.Januaryecalendar.Februaryforam descontinuadas e substituídas porcalendar.JANUARYecalendar.FEBRUARY. (Contribuição de Prince Roshan em gh-103636.)codecs: useopen()em vez decodecs.open(). (gh-133038)codeobject.co_lnotab: use thecodeobject.co_lines()method instead.-
utcnow(): usedatetime.datetime.now(tz=datetime.UTC).utcfromtimestamp(): usedatetime.datetime.fromtimestamp(timestamp, tz=datetime.UTC).
gettext: o valor de plural deve ser um número inteiro.-
O parâmetro debug_override de
cache_from_source()foi descontinuado: em vez disso, use o parâmetro optimization.
-
Interface de tupla
EntryPoints.Noneimplícito nos valores de retorno.
logging: o métodowarn()foi descontinuado desde o Python 3.3, usewarning().mailbox: o uso da entrada StringIO e do modo de texto foi descontinuado; em vez disso, use BytesIO e o modo binário.os: Callingos.register_at_fork()in a multi-threaded process.os.path:os.path.commonprefix()is deprecated, useos.path.commonpath()for path prefixes. Theos.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: um valor de tupla para o parâmetro exc_info foi descontinuado, use uma instância de exceção.re: regras mais rigorosas agora são aplicadas para referências numéricas de grupos e nomes de grupos em expressões regulares. Apenas a sequência de dígitos ASCII agora é aceita como referência numérica. O nome do grupo em padrões de bytes e strings de substituição agora pode conter apenas letras e dígitos ASCII e sublinhado. (Contribuição de Serhiy Storchaka em gh-91760.)shutil: o parâmetro onerror dermtree()foi descontinuado no Python 3.12; use o parâmetro onexc.Protocolos e opções de
sslssl.SSLContextsem argumento de protocolo foi descontinuado.ssl.SSLContext:set_npn_protocols()eselected_npn_protocol()foram descontinuados: use ALPN.Opções de
ssl.OP_NO_SSL*Opções 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 de
threading:threading.Condition.notifyAll(): usenotify_all().threading.Event.isSet(): useis_set().threading.Thread.isDaemon(),threading.Thread.setDaemon(): use o atributothreading.Thread.daemon.threading.Thread.getName(),threading.Thread.setName(): use o atributothreading.Thread.name.threading.currentThread(): usethreading.current_thread().threading.activeCount(): usethreading.active_count().
A classe interna
typing._UnionGenericAliasnão é mais usada para implementartyping.Union. Para preservar a compatibilidade com usuários que utilizam esta classe privada, uma correção de compatibilidade será fornecida pelo menos até a versão 3.17 do Python. (Contribuição de Jelle Zijlstra em gh-105499.)unittest.IsolatedAsyncioTestCase: foi descontinuado retornar um valor que não sejaNonede um caso de teste.Funções descontinuadas de
urllib.parse: useurlparse()splitattr()splithost()splitnport()splitpasswd()splitport()splitquery()splittag()splittype()splituser()splitvalue()to_bytes()
wsgiref:SimpleHandler.stdout.write()não deve fazer gravações parciais.xml.etree.ElementTree: testar o valor verdade de umElementestá descontinuado. Em um lançamento futuro isso sempre retornaráTrue. Em vez disso, prefira os testes explícitoslen(elem)ouelem is not None.sys._clear_type_cache()está descontinuada: usesys._clear_internal_caches().
Soft deprecations¶
There are no plans to remove soft deprecated APIs.
re.match()andre.Pattern.match()are now soft deprecated in favor of the newre.prefixmatch()andre.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 usematch(), while new code should preferprefixmatch(). See prefixmatch() vs. match().(Contributed by Gregory P. Smith in gh-86519 and Hugo van Kemenade in gh-148100.)
Using
'F'and'D'format type codes of thestructmodule now are soft deprecated in favor of two-letter forms'Zf'and'Zd'. (Contributed by Sergey B Kirpichev in gh-121249.)
Descontinuações na API C¶
Remoção pendente no Python 3.18¶
As seguintes funções privadas estão descontinuado e planejadas para remoção no Python 3.18:
_PyBytes_Join(): usePyBytes_Join()._PyDict_GetItemStringWithError(): usePyDict_GetItemStringRef()._PyDict_Pop(): usePyDict_Pop()._PyLong_Sign(): usePyLong_GetSign()._PyLong_FromDigits()e_PyLong_New(): usePyLongWriter_Create()._PyThreadState_UncheckedGet(): usePyThreadState_GetUnchecked()._PyUnicode_AsString(): usePyUnicode_AsUTF8()._PyUnicodeWriter_Init(): substitua_PyUnicodeWriter_Init(&writer)comwriter = PyUnicodeWriter_Create(0)._PyUnicodeWriter_Finish(): substitua_PyUnicodeWriter_Finish(&writer)porPyUnicodeWriter_Finish(writer)._PyUnicodeWriter_Dealloc(): substitua_PyUnicodeWriter_Dealloc(&writer)porPyUnicodeWriter_Discard(writer)._PyUnicodeWriter_WriteChar(): substituta_PyUnicodeWriter_WriteChar(&writer, ch)comPyUnicodeWriter_WriteChar(writer, ch)._PyUnicodeWriter_WriteStr(): substitua_PyUnicodeWriter_WriteStr(&writer, str)porPyUnicodeWriter_WriteStr(writer, str)._PyUnicodeWriter_WriteSubstring(): substitua_PyUnicodeWriter_WriteSubstring(&writer, str, start, end)porPyUnicodeWriter_WriteSubstring(writer, str, start, end)._PyUnicodeWriter_WriteASCIIString(): substitua_PyUnicodeWriter_WriteASCIIString(&writer, str)porPyUnicodeWriter_WriteASCII(writer, str)._PyUnicodeWriter_WriteLatin1String(): substitua_PyUnicodeWriter_WriteLatin1String(&writer, str)porPyUnicodeWriter_WriteUTF8(writer, str)._PyUnicodeWriter_Prepare(): (sem substituto)._PyUnicodeWriter_PrepareKind(): (sem substituto)._Py_HashPointer(): usePy_HashPointer()._Py_fopen_obj(): usePy_fopen().PyGen_New(): (no replacement).PyGen_NewWithQualName(): (no replacement).PyCoro_New(): (no replacement).PyAsyncGen_New(): (no replacement).
O projeto pythoncapi-compat pode ser usado para obter essas novas funções públicas no Python 3.13 e versões anteriores. (Contribuição de Victor Stinner em gh-128863.)
Remoção pendente no Python 3.19¶
PEP 456 embedders support for the string hashing scheme definition.
Remoção pendente no Python 3.20¶
_PyObject_CallMethodId(),_PyObject_GetAttrId()e_PyUnicode_FromId()foram descontinuadas desde o 3.15 e serão removidas na versão 3.20. Em vez delas, usePyUnicode_InternFromString()and armazene em cache o resultado no estado do módulo e chamePyObject_CallMethod()ouPyObject_GetAttr(). (Contribuição de Victor Stinner em gh-141049.)O campo
cvalemPyComplexObject(gh-128813). UsePyComplex_AsCComplex()ePyComplex_FromCComplex()para converter um número complexo Python de/para a representação C dePy_complex.Macros
Py_MATH_PIlePy_MATH_El.
Remoção pendente em versões futuras¶
As APIs a seguir foram descontinuadas e serão removidas, embora atualmente não haja uma data agendada para sua remoção.
Py_TPFLAGS_HAVE_FINALIZE: desnecessária desde o Python 3.8.PySlice_GetIndicesEx(): usePySlice_Unpack()ePySlice_AdjustIndices().PyUnicode_READY(): desnecessário desde o Python 3.12PyErr_Display(): usePyErr_DisplayException()._PyErr_ChainExceptions(): use_PyErr_ChainExceptions1().O membro
PyBytesObject.ob_shash: chamePyObject_Hash().API do Thread Local Storage (TLS):
PyThread_ReInitTLS(): desnecessário desde o Python 3.7.