O que há de novo no Python 3.14¶
- Editor:
Hugo van Kemenade
Esse artigo explica os novos recursos no Python 3.14. comparado ao 3.13.
Para detalhes completos, veja o changelog.
Ver também
PEP 745 – Cronograma de lançamento do Python 3.14
Nota
Os usuários de pré-lançamento devem estar cientes de que este documento está atualmente em forma de rascunho. Ele será atualizado substancialmente à medida que o Python 3.14 caminha para seu lançamento estável, portanto vale a pena conferir mesmo depois de ler as versões anteriores.
Resumo – destaques da versão¶
O Python 3.14 beta é o pré-lançamento da próxima versão da linguagem de programação Python, com uma mistura de alterações na linguagem, na implementação e na biblioteca padrão.
As maiores mudanças no implementação incluem as strings template (PEP 750), a avaliação adiada de anotações (PEP 649) e um novo tipo de interpretador que usa a chamada de cauda.
As alterações na biblioteca incluem o acréscimo de um novo módulo, annotationlib
(PEP 749), para introspecção e empacotamento de anotações (PEP 649), um novo módulo, compression.zstd
, para suporte ao Zstandard (PEP 784), além de destaque de sintaxe no REPL, bem como descontinuações e remoções habituais e melhorias na facilidade de uso e correções.
Alterações incompatíveis¶
Em plataformas diferentes de macOS e Windows, o método de início padrão para multiprocessing
e ProcessPoolExecutor
muda de fork para forkserver.
Consulte (1) e (2) para detalhes.
Se você encontrar NameError
s ou erros de serialização com pickle vindos de multiprocessing
ou concurrent.futures
, consulte as restrições do forkserver.
O interpretador evita algumas modificações na contagem de referências internamente quando é seguro fazê-lo. Isso pode levar a valores diferentes retornados de sys.getrefcount()
e Py_REFCNT()
em comparação com versões anteriores do Python. Consulte abaixo para obter detalhes.
Novas funcionalidades¶
PEP 779: Python com threads livres é oficialmente suportado¶
A construção do Python com threads livres agora é suportada e não mais experimental. Este é o início da fase II, na qual o Python com threads livres é oficialmente suportado, mas ainda é opcional.
Estamos confiantes de que o projeto está no caminho certo e agradecemos a dedicação contínua de todos que trabalham para deixar o modo threads livres pronto para uma adoção mais ampla na comunidade Python.
Com essas recomendações e a aceitação desta PEP, nós, como comunidade de desenvolvedores Python, devemos anunciar amplamente que threads livres é uma opção de construção do Python suportada agora e no futuro, e que ela não será removida sem um cronograma de descontinuação adequado.
Qualquer decisão de transição para a fase III, com o uso de threads livres como versão padrão ou única do Python, ainda está indefinida e depende de muitos fatores, tanto dentro do próprio CPython quanto da comunidade. Esta decisão é para o futuro.
PEP 734: múltiplos interpretadores na stdlib¶
O ambiente de execução do CPython permite a execução simultânea de várias cópias do Python no mesmo processo, há mais de 20 anos. Cada uma dessas cópias separadas é chamada de “interpretador”. No entanto, o recurso estava disponível apenas por meio da API C.
Essa limitação foi removida na versão 3.14, com o novo módulo concurrent.interpreters
.
Há pelo menos dois motivos importantes pelos quais vale a pena considerar o uso de múltiplos interpretadores:
eles oferecem suporte a um novo modelo (para Python) de simultaneidade, amigável ao ser humano
verdadeiro paralelismo multi-core
Para alguns casos de uso, a simultaneidade em software permite eficiência e pode simplificar o software em alto nível. Ao mesmo tempo, implementar e manter todos os tipos de simultaneidade, exceto as mais simples, costuma ser uma luta para o cérebro humano. Isso se aplica especialmente a threads simples (por exemplo, threading
), onde toda a memória é compartilhada entre todas as threads.
Com múltiplos interpretadores isolados, você pode aproveitar uma classe de modelos de simultaneidade, como CSP ou o modelo de ator, que obtiveram sucesso em outras linguagens de programação, como Smalltalk, Erlang, Haskell e Go. Pense em múltiplos interpretadores como threads, mas com compartilhamento opt-in.
Sobre o paralelismo multinúcleo: a partir da versão 3.12, os interpretadores agora estão suficientemente isolados uns dos outros para serem usados em paralelo. (Veja PEP 684.) Isso destrava uma variedade de casos de uso intensivos de CPU para Python que eram limitados pela GIL.
O uso de múltiplos interpretadores é semelhante em muitos aspectos ao multiprocessing
, pois ambos fornecem “processos” lógicos isolados que podem ser executados em paralelo, sem compartilhamento por padrão. No entanto, ao usar múltiplos interpretadores, uma aplicação usará menos recursos do sistema e operará com mais eficiência (já que permanece dentro do mesmo processo). Pense em múltiplos interpretadores como se tivessem o isolamento de processos com a eficiência de threads.
Embora o recurso já exista há décadas, múltiplos interpretadores não têm sido amplamente utilizados devido à baixa conscientização e à ausência de um módulo da stdlib. Consequentemente, eles atualmente apresentam diversas limitações notáveis, que melhorarão significativamente agora que o recurso finalmente está se tornando popular.
Limitações atuais:
iniciar cada interpretador ainda não foi otimizado
cada interpretador usa mais memória do que o necessário (trabalharemos em seguida no compartilhamento interno extensivo entre interpretadores)
não há muitas opções ainda para realmente compartilhar objetos ou outros dados entre interpretadores (além de
memoryview
)muitos módulos de extensão no PyPI ainda não são compatíveis com múltiplos interpretadores (os módulos de extensão stdlib são compatíveis)
a abordagem para escrever aplicações que usam vários interpretadores isolados é, em grande parte, desconhecida para usuários do Python, por enquanto
O impacto dessas limitações dependerá de futuras melhorias no CPython, do uso dos interpretadores e do que a comunidade resolver por meio dos pacotes PyPI. Dependendo do caso de uso, as limitações podem não ter muito impacto, então experimente!
Além disso, versões futuras do CPython reduzirão ou eliminarão a sobrecarga e fornecerão utilitários menos apropriados no PyPI. Enquanto isso, a maioria das limitações também pode ser solucionada por meio de módulos de extensão, o que significa que os pacotes do PyPI podem preencher qualquer lacuna da versão 3.14 e até mesmo da versão 3.12, onde os interpretadores foram finalmente isolados adequadamente e pararam de compartilhar a GIL. Da mesma forma, esperamos ver gradualmente bibliotecas no PyPI para abstrações de alto nível sobre os interpretadores.
Em relação aos módulos de extensão, estamos trabalhando para atualizar alguns projetos PyPI, bem como ferramentas como Cython, pybind11, nanobind e PyO3. As etapas para isolar um módulo de extensão podem ser encontradas em Isolando módulos de extensão. O isolamento de um módulo tem muitas sobreposições com o que é necessário para oferecer suporte a threads livres, portanto, o trabalho contínuo da comunidade nessa área ajudará a acelerar o suporte a múltiplos interpretadores.
Também adicionado no 3.14: concurrent.futures.InterpreterPoolExecutor.
Ver também
PEP 750: strings template¶
Literais de string template (t-strings) são uma generalização de f-strings, usando um t
no lugar do prefixo f
. Em vez de serem avaliadas como str
, as t-strings são avaliadas como um novo tipo string.templatelib.Template
:
from string.templatelib import Template
name = "Mundo"
template: Template = t"Olá {name}"
O modelo pode então ser combinado com funções que operam na estrutura do template para produzir um str
ou um resultado semelhante a uma string. Por exemplo, sanitizando a entrada:
evil = "<script>alert('evil')</script>"
template = t"<p>{evil}</p>"
assert html(template) == "<p><script>alert('evil')</script></p>"
Como outro exemplo, gerando atributos HTML a partir de dados:
attributes = {"src": "shrubbery.jpg", "alt": "looks nice"}
template = t"<img {attributes}>"
assert html(template) == '<img src="shrubbery.jpg" alt="looks nice" />'
Em comparação com o uso de uma f-string, a função html
tem acesso a atributos de modelo que contêm as informações originais: strings estáticas, interpolações e valores do escopo original. Ao contrário das abordagens de modelo existentes, as t-strings são construídas a partir da sintaxe e das regras conhecidas das f-strings. Os sistemas de template, portanto, se beneficiam das ferramentas Python, pois estão muito mais próximos da linguagem Python, da sintaxe, do escopo e de outros aspectos.
Escrever manipuladores de template é simples:
from string.templatelib import Template, Interpolation
def lower_upper(template: Template) -> str:
"""Renderiza as partes estáticas em minúsculas e as interpolações em maiúsculas."""
parts: list[str] = []
for item in template:
if isinstance(item, Interpolation):
parts.append(str(item.value).upper())
else:
parts.append(item.lower())
return "".join(parts)
name = "mundo"
assert lower_upper(t"OLÁ {name}") == "olá MUNDO"
Com isso, os desenvolvedores podem escrever sistemas de modelo para higienizar SQL, fazer operações de shell seguras, melhorar o registro, abordar ideias modernas em desenvolvimento web (HTML, CSS e assim por diante) e implementar DSLs comerciais leves e personalizadas.
(Contribuição de Jim Baker, Guido van Rossum, Paul Everitt, Koudai Aono, Lysandros Nikolaou, Dave Peck, Adam Turner, Jelle Zijlstra, Bénédikt Tran e Pablo Galindo Salgado em gh-132661.)
Ver também
PEP 768: interface segura para depurador externo para o CPython¶
PEP 768 introduz uma interface de depuração sem sobrecarga que permite que depuradores e profilers se conectem com segurança a processos Python em execução. Esta é uma melhoria significativa nos recursos de depuração do Python, permitindo que depuradores renunciem a alternativas inseguras. Veja abaixo para saber como este recurso é utilizado para implementar os recursos de conexão remota do novo módulo pdb
.
A nova interface fornece pontos de execução seguros para anexar código do depurador sem modificar o caminho de execução normal do interpretador ou adicionar sobrecarga de tempo de execução. Isso permite que as ferramentas inspecionem e interajam com aplicações Python em tempo real sem interrompê-las ou reiniciá-las — um recurso crucial para sistemas de alta disponibilidade e ambientes de produção.
Para conveniência, o CPython implementa essa interface por meio do módulo sys
com uma função sys.remote_exec()
:
sys.remote_exec(pid, script_path)
Esta função permite o envio de código Python para ser executado em um processo de destino no próximo ponto de execução seguro. No entanto, os autores da ferramenta também podem implementar o protocolo diretamente, conforme descrito no PEP, que detalha os mecanismos subjacentes usados para anexar com segurança a processos em execução.
Aqui está um exemplo simples que inspeciona tipos de objetos em um processo Python em execução:
import os import sys import tempfile # Cria um script temporário with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f: script_path = f.name f.write(f"import my_debugger; my_debugger.connect({os.getpid()})") try: # Executa no processo com PID 1234 print("Vejam! Eis uma oferta!:") sys.remote_exec(1234, script_path) finally: os.unlink(script_path)
A interface de depuração foi cuidadosamente projetada com a segurança em mente e inclui vários mecanismos para controlar o acesso:
Uma variável de ambiente
PYTHON_DISABLE_REMOTE_DEBUG
.Uma opção de linha de comando
-X disable-remote-debug
.Um sinalizador de configuração
--without-remote-debug
para desabilitar completamente o recurso no momento da construção.
Um detalhe importante da implementação é que a interface se baseia no laço de avaliação existente do interpretador e nos pontos seguros, garantindo sobrecarga zero durante a execução normal e, ao mesmo tempo, fornecendo uma maneira confiável para processos externos coordenarem operações de depuração.
(Contribuição de Pablo Galindo Salgado, Matt Wozniski e Ivona Stojanovic em gh-131591.)
Ver também
PEP 784: adicionando Zstandard à biblioteca padrão¶
O novo pacote compression
contém os módulos compression.lzma
, compression.bz2
, compression.gzip
e compression.zlib
, que reexportam os módulos lzma
, bz2
, gzip
e zlib
, respectivamente. Os novos nomes de importação em compression
são os nomes canônicos para a importação desses módulos de compactação daqui para frente. No entanto, os nomes dos módulos existentes não foram descontinuados. Qualquer descontinuação ou remoção dos módulos de compressão existentes ocorrerá no máximo cinco anos após o lançamento da versão 3.14.
O novo módulo compression.zstd
fornece APIs de compactação e descompactação para o formato Zstandard por meio de ligações à biblioteca zstd do Meta. O Zstandard é um formato de compactação amplamente adotado, altamente eficiente e rápido. Além das APIs introduzidas em compression.zstd
, o suporte para leitura e gravação de arquivos compactados do Zstandard foi adicionado aos módulos tarfile
, zipfile
e shutil
.
Aqui está um exemplo de uso do novo módulo para compactar alguns dados:
from compression import zstd
import math
data = str(math.pi).encode() * 20
compressed = zstd.compress(data)
ratio = len(compressed) / len(data)
print(f"Foi alcançada uma taxa de compactação de {ratio}")
Como pode ser visto, a API é semelhante às APIs dos módulos lzma
e bz2
.
(Contribuição de Emma Harper Smith, Adam Turner, Gregory P. Smith, Tomas Roun, Victor Stinner e Rogdham em gh-132983.)
Ver também
Anexação remota a um processo Python em execução com PDB¶
O módulo pdb
agora suporta anexação remota a um processo Python em execução usando uma nova opção de linha de comando -p PID
:
python -m pdb -p 1234
Isso se conectará ao processo Python com o PID fornecido e permitirá que você o depure interativamente. Observe que, devido ao funcionamento do interpretador Python, a conexão a um processo remoto bloqueado em uma chamada de sistema ou aguardando E/S só funcionará quando a próxima instrução de bytecode for executada ou quando o processo receber um sinal.
Este recurso usa PEP 768 e a função sys.remote_exec()
para anexar ao processo remoto e enviar os comandos PDB a ele.
(Contribuição de Matt Wozniski e Pablo Galindo em gh-131591.)
Ver também
PEP 758 – permite expressões except e except* sem parênteses¶
As expressões except
e except*
agora permitem a omissão de parênteses quando há vários tipos de exceção e a cláusula as
não é usada. Por exemplo, as seguintes expressões agora são válidas:
try:
connect_to_server()
except TimeoutError, ConnectionRefusedError:
print("Problema de rede encontrado.")
# O mesmo se aplica a except* (para grupos de exceções):
try:
connect_to_server()
except* TimeoutError, ConnectionRefusedError:
print("Problema de rede encontrado.")
Confira PEP 758 para mais detalhes.
(Contribuição de Pablo Galindo e Brett Cannon em gh-131831.)
Ver também
PEP 649 e 749: avaliação adiada de anotações¶
As anotações em função, classes e módulos não são mais avaliados de forma ansiosa. Em vez disso, as anotações são armazenadas em uma função de anotação com propósito especial e avaliadas somente quando necessário (exceto se from __future__ import annotations
for usado). Isso está especificado nas PEP 649 e PEP 749.
Essa alteração foi projetada para tornar anotações em Python mais eficientes e mais utilizáveis na maioria das circunstâncias. O custo em tempo de execução para definir anotação é minimizado, mas continua sendo possível introspectar anotação em tempo de execução. Não é mais necessário incluir anotação em string se eles contiverem referência futura.
O novo módulo annotationlib
fornece ferramentas para inspecionar anotação adiada. A anotação pode ser avaliada nos formatos VALUE
(que avalia anotações para valores em tempo de execução, semelhante ao comportamento nas versões anteriores do Python), FORWARDREF
(que substitui nomes indefinidos por marcadores especiais) e STRING
(que retorna anotações como strings).
Este exemplo mostra como esses formatos se comportam:
>>> from annotationlib import get_annotations, Format
>>> def func(arg: Undefined):
... pass
>>> get_annotations(func, format=Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'Undefined' is not defined
>>> get_annotations(func, format=Format.FORWARDREF)
{'arg': ForwardRef('Undefined', owner=<function func at 0x...>)}
>>> get_annotations(func, format=Format.STRING)
{'arg': 'Undefined'}
Implicações para o código anotado¶
Se você definir anotação em seu código (por exemplo, para uso com um verificador de tipo estático), essa alteração provavelmente não o afetará: você pode continuar escrevendo anotação da mesma forma que fazia com as versões anteriores de Python.
É provável que você consiga remover as strings entre aspas em anotações, que são frequentemente usadas para referência futura. Da mesma forma, se você usar from __future__ import annotations
para evitar ter que escrever string em anotação, poderá remover essa importação se você for manter seu código apenas para Python 3.14 e mais recentes. No entanto, se você depende de bibliotecas de terceiros que leem anotações, essas bibliotecas podem precisar de alterações no suporte a anotações sem aspas para funcionaram como esperado.
Implicações para leitores de __annotations__
¶
Se o seu código lê o atributo __annotations__
dos objetos, talvez você queira fazer alterações para prover suporte a código que depende da avaliação adiada de anotações. Por exemplo, talvez você queira usar annotationlib.get_annotations()
com o formato FORWARDREF
, como o módulo dataclasses
faz agora.
O pacote externo typing_extensions fornece compatibilidade retroativa parcial de algumas das funcionalidades do módulo annotationlib
, como a enumeração Format
e a função get_annotations()
. Eles podem ser usados para escrever código com versão-cruzada que aproveite as vantagens do novo comportamento em Python 3.14.
from __future__ import annotations
¶
No Python 3.7, a PEP 563 introduziu a diretiva from __future__ import annotations
, que transforma todas as anotações em strings. Essa diretiva agora é considerada descontinuada e espera-se que seja removida em uma futura versão do Python. No entanto, essa remoção só ocorrerá depois que Python 3.13, a última versão sem avaliação adiada de anotação, chegar ao fim de sua vida útil em 2029. No Python 3.14, o comportamento do código que usa from __future__ import annotations
não foi alterado.
(Contribuição de Jelle Zijlstra em gh-119180, PEP 649 foi escrita por Larry Hastings.)
Mensagens de erro melhoradas¶
O interpretador agora fornece sugestões úteis ao detectar erros de digitação em palavras reservadas do Python. Ao encontrar uma palavra que se assemelha muito a uma palavra reservada do Python, o interpretador sugere a palavra reservada correta na mensagem de erro. Esse recurso ajuda os programadores a identificar e corrigir rapidamente erros comuns de digitação. Por exemplo:
>>> whille True: ... pass Traceback (most recent call last): File "<stdin>", line 1 whille True: ^^^^^^ SyntaxError: invalid syntax. Did you mean 'while'? >>> asynch def fetch_data(): ... pass Traceback (most recent call last): File "<stdin>", line 1 asynch def fetch_data(): ^^^^^^ SyntaxError: invalid syntax. Did you mean 'async'? >>> async def foo(): ... awaid fetch_data() Traceback (most recent call last): File "<stdin>", line 2 awaid fetch_data() ^^^^^ SyntaxError: invalid syntax. Did you mean 'await'? >>> raisee ValueError("Error") Traceback (most recent call last): File "<stdin>", line 1 raisee ValueError("Error") ^^^^^^ SyntaxError: invalid syntax. Did you mean 'raise'?
Embora o recurso se concentre nos casos mais comuns, algumas variações de erros ortográficos ainda podem resultar em erros de sintaxe comuns. (Contribuição de Pablo Galindo em gh-132449.)
Quando a atribuição de desempacotamento falha devido a um número incorreto de variáveis, a mensagem de erro exibe o número de valores recebidos em mais casos do que antes. (Contribuição de Tushar Sadhwani em gh-122239.)
>>> x, y, z = 1, 2, 3, 4 Traceback (most recent call last): File "<stdin>", line 1, in <module> x, y, z = 1, 2, 3, 4 ^^^^^^^ ValueError: too many values to unpack (expected 3, got 4)
Instruções
elif
que seguem um blocoelse
agora têm uma mensagem de erro específica. (Contribuição de Steele Farnsworth em gh-129902.)>>> if who == "eu": ... print("Sou eu!") ... else: ... print("Não sou eu!") ... elif who is None: ... print("Quem é?") File "<stdin>", line 5 elif who is None: ^^^^ SyntaxError: 'elif' block follows an 'else' block
Se uma instrução (
pass
,del
,return
,yield
,raise
,break
,continue
,assert
,import
,from
) for passada para Expressões condicionais apóselse
, ou uma dentrepass
,break
oucontinue
for passada antes deif
, a mensagem de erro destacará onde oexpression
é necessário. (Contribuição de Sergey Miryanov em gh-129515.)>>> x = 1 if True else pass Traceback (most recent call last): File "<string>", line 1 x = 1 if True else pass ^^^^ SyntaxError: expected expression after 'else', but statement is given >>> x = continue if True else break Traceback (most recent call last): File "<string>", line 1 x = continue if True else break ^^^^^^^^ SyntaxError: expected expression before 'if', but statement is given
Quando strings fechadas incorretamente são detectadas, a mensagem de erro sugere que a string pode ser parte da string. (Contribuição de Pablo Galindo em gh-88535.)
>>> "O objeto interessante "O objeto interessante" é muito importante" Traceback (most recent call last): SyntaxError: invalid syntax. Is this intended to be part of the string?
Quando strings têm prefixos incompatíveis, o erro agora mostra quais prefixos são incompatíveis. (Contribuição de Nikita Sobolev em gh-133197.)
>>> ub'abc' File "<python-input-0>", line 1 ub'abc' ^^ SyntaxError: 'u' and 'b' prefixes are incompatible
Mensagens de erro aprimoradas ao usar
as
com alvos incompatíveis em:Importações:
import ... as ...
Importações “from”:
from ... import ... as ...
Manipuladores “except”:
except ... as ...
Casos de correspondência de padrão:
case ... as ...
(Contribuição de Nikita Sobolev in gh-123539, gh-123562 e gh-123440.)
>>> import ast as arr[0] File "<python-input-1>", line 1 import ast as arr[0] ^^^^^^ SyntaxError: cannot use subscript as import target
Mensagem de erro aprimorada ao tentar adicionar uma instância de um tipo não-hasheável a um
dict
ouset
. (Contribuição de CF Bolz-Tereick e Victor Stinner em gh-132828.)>>> s = set() >>> s.add({'pages': 12, 'grade': 'A'}) Traceback (most recent call last): File "<python-input-1>", line 1, in <module> s.add({'pages': 12, 'grade': 'A'}) ~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: cannot use 'dict' as a set element (unhashable type: 'dict') >>> d = {} >>> l = [1, 2, 3] >>> d[l] = 12 Traceback (most recent call last): File "<python-input-4>", line 1, in <module> d[l] = 12 ~^^^ TypeError: cannot use 'list' as a dict key (unhashable type: 'list')
PEP 741: API C de configuração do Python¶
Adiciona uma PyInitConfig API C para configurar a inicialização do Python sem depender de estruturas C e a capacidade de fazer alterações compatíveis com ABI no futuro.
Conclui a PyConfig API C da PEP 587 adicionando PyInitConfig_AddModule()
que pode ser usado para adicionar um módulo de extensão embutido; recurso anteriormente chamado de “inittab”.
Adiciona as funções PyConfig_Get()
e PyConfig_Set()
para obter e definir a configuração de tempo de execução atual.
A “Configuração de Inicialização do Python” da PEP 587 unificou todas as maneiras de configurar a inicialização do Python. Esta PEP também unifica a configuração da pré-inicialização do Python e a inicialização do Python em uma única API. Além disso, esta PEP oferece apenas uma opção para incorporar o Python, em vez de ter duas opções, “Python” e “Isolated” (PEP 587), simplificando ainda mais a API.
A API PyConfig da PEP 587 de nível inferior permanece disponível para casos de uso com um nível intencionalmente mais alto de acoplamento aos detalhes de implementação do CPython (como emular a funcionalidade completa da CLI do CPython, incluindo seus mecanismos de configuração).
(Contribuição de Victor Stinner em gh-107954.)
Ver também
Capacidades de introspecção assíncrona¶
Foi adicionada uma nova interface de linha de comando para inspecionar processos Python em execução usando tarefas assíncronas, disponível via:
python -m asyncio ps PID
Esta ferramenta inspeciona o ID do processo (PID) fornecido e exibe informações sobre as tarefas assíncronas em execução. Ela gera uma tabela de tarefas: uma lista simples de todas as tarefas, seus nomes, suas pilhas de corrotinas e quais tarefas as aguardam.
python -m asyncio pstree PID
Esta ferramenta busca as mesmas informações, mas renderiza uma árvore de chamadas assíncrona visual, mostrando os relacionamentos das corrotinas em um formato hierárquico. Este comando é particularmente útil para depurar programas assíncronos de longa execução ou travados. Ele pode ajudar os desenvolvedores a identificar rapidamente onde um programa está bloqueado, quais tarefas estão pendentes e como as corrotinas estão encadeadas.
Por exemplo, dado este código:
import asyncio
async def play(track):
await asyncio.sleep(5)
print(f"🎵 Finished: {track}")
async def album(name, tracks):
async with asyncio.TaskGroup() as tg:
for track in tracks:
tg.create_task(play(track), name=track)
async def main():
async with asyncio.TaskGroup() as tg:
tg.create_task(
album("Sundowning", ["TNDNBTG", "Levitate"]), name="Sundowning")
tg.create_task(
album("TMBTE", ["DYWTYLM", "Aqua Regia"]), name="TMBTE")
if __name__ == "__main__":
asyncio.run(main())
Executar a nova ferramenta no processo em execução produzirá uma tabela como esta:
python -m asyncio ps 12345
tid task id task name coroutine stack awaiter chain awaiter name awaiter id
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
1935500 0x7fc930c18050 Task-1 TaskGroup._aexit -> TaskGroup.__aexit__ -> main 0x0
1935500 0x7fc930c18230 Sundowning TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fa50 TMBTE TaskGroup._aexit -> TaskGroup.__aexit__ -> album TaskGroup._aexit -> TaskGroup.__aexit__ -> main Task-1 0x7fc930c18050
1935500 0x7fc93173fdf0 TNDNBTG sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32510 Levitate sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album Sundowning 0x7fc930c18230
1935500 0x7fc930d32890 DYWTYLM sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
1935500 0x7fc93161ec30 Aqua Regia sleep -> play TaskGroup._aexit -> TaskGroup.__aexit__ -> album TMBTE 0x7fc93173fa50
ou uma árvore como esta:
python -m asyncio pstree 12345
└── (T) Task-1
└── main example.py:13
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) Sundowning
│ └── album example.py:8
│ └── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
│ └── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
│ ├── (T) TNDNBTG
│ │ └── play example.py:4
│ │ └── sleep Lib/asyncio/tasks.py:702
│ └── (T) Levitate
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) TMBTE
└── album example.py:8
└── TaskGroup.__aexit__ Lib/asyncio/taskgroups.py:72
└── TaskGroup._aexit Lib/asyncio/taskgroups.py:121
├── (T) DYWTYLM
│ └── play example.py:4
│ └── sleep Lib/asyncio/tasks.py:702
└── (T) Aqua Regia
└── play example.py:4
└── sleep Lib/asyncio/tasks.py:702
Se um ciclo for detectado no grafo async await (o que pode indicar um problema de programação), a ferramenta levanta um erro e lista os caminhos de ciclo que impedem a construção da árvore:
python -m asyncio pstree 12345
ERROR: await-graph contains cycles - cannot print a tree!
cycle: Task-2 → Task-3 → Task-2
(Contribuição de Pablo Galindo, Łukasz Langa, Yury Selivanov e Marta Gomez Macias em gh-91048.)
Um novo tipo de interpretador¶
Um novo tipo de interpretador foi adicionado ao CPython. Ele utiliza chamadas de cauda entre pequenas funções C que implementam opcodes Python individuais, em vez de uma única instrução case C extensa. Para alguns compiladores mais recentes, este interpretador oferece desempenho significativamente melhor. Dados preliminares em nossas máquinas sugerem um código Python até 30% mais rápido e uma média geométrica de 3 a 5% mais rápido no pyperformance
, dependendo da plataforma e da arquitetura. A linha de base é o Python 3.14, construído com o Clang 19 sem este novo interpretador.
Atualmente, este interpretador funciona apenas com o Clang 19 e versões mais recentes em arquiteturas x86-64 e AArch64. No entanto, esperamos que uma versão futura do GCC também ofereça suporte a ele.
Este recurso é opcional por enquanto. Recomendamos fortemente habilitar a otimização guiada por perfil com o novo interpretador, pois é a única configuração que testamos e podemos validar seu desempenho aprimorado. Para mais informações sobre como construir Python, consulte --with-tail-call-interp
.
Nota
Isso não deve ser confundido com a otimização de chamada de cauda de funções Python, que atualmente não está implementada no CPython.
Este novo tipo de interpretador é um detalhe de implementação interna do interpretador CPython. Ele não altera em nada o comportamento visível dos programas Python. Pode melhorar o desempenho deles, mas não altera nada mais.
Atenção
Esta seção relatou anteriormente um aumento de velocidade médio geométrico de 9 a 15%. Desde então, esse número foi cuidadosamente revisado reduzindo para 3 a 5%. Embora esperemos que os resultados de desempenho sejam melhores do que os relatados, nossas estimativas são mais conservadoras devido a um bug do compilador encontrado no Clang/LLVM 19, que faz com que o interpretador normal seja mais lento. Não tínhamos conhecimento desse bug, resultando em resultados imprecisos. Pedimos sinceras desculpas por comunicar resultados que eram precisos apenas para o LLVM v19.1.x e v20.1.0. Neste meio-tempo, o bug foi corrigido no LLVM v20.1.1 e para o próximo v21.1, mas permanecerá sem correção para o LLVM v19.1.x e v20.1.0. Portanto, quaisquer benchmarks com essas versões do LLVM podem produzir números imprecisos. (Agradecimentos a Nelson Elhage por trazer isso à tona.)
(Contribuição de Ken Jin em gh-128563, com ideias sobre como implementar isso em CPython por Mark Shannon, Garrett Gu, Haoran Xu e Josh Haberman.)
Modo de threads livres¶
O modo de threads livres (PEP 703), adicionado inicialmente na versão 3.13, foi significativamente aprimorado. A implementação descrita no PEP 703 foi concluída, incluindo alterações na API C, e soluções temporárias no interpretador foram substituídas por soluções mais permanentes. O interpretador adaptativo especializado (PEP 659) agora está habilitado no modo de threads livres, o que, juntamente com muitas outras otimizações, melhora significativamente seu desempenho. A perda de desempenho em código de thread única no modo de threads livres agora é de aproximadamente 5 a 10%, dependendo da plataforma e do compilador C utilizados.
Este trabalho foi realizado por muitos colaboradores: Sam Gross, Matt Page, Neil Schemenauer, Thomas Wouters, Donghee Na, Kirill Podoprigora, Ken Jin, Itamar Oren, Brett Simmers, Dino Viehland, Nathan Goldbaum, Ralf Gommers, Lysandros Nikolaou, Kumar Aditya, Edgar Margffoy e muitos outros.
Alguns desses colaboradores são empregados da Meta, que continuou a fornecer recursos de engenharia significativos para dar suporte a este projeto.
A partir da versão 3.14, ao compilar módulos de extensão para a construção do CPython com threads livres no Windows, a variável de pré-processador Py_GIL_DISABLED
agora precisa ser especificada pelo backend de construção, pois não será mais determinada automaticamente pelo compilador C. Para um interpretador em execução, a configuração usada em tempo de compilação pode ser encontrada usando sysconfig.get_config_var()
.
Syntax highlighting in PyREPL¶
The default interactive shell now highlights Python syntax as you
type. The feature is enabled by default unless the
PYTHON_BASIC_REPL
environment is set or any color-disabling
environment variables are used. See Controlando cores for
details.
The default color theme for syntax highlighting strives for good contrast
and uses exclusively the 4-bit VGA standard ANSI color codes for maximum
compatibility. The theme can be customized using an experimental API
_colorize.set_theme()
. This can be called interactively, as well as
in the PYTHONSTARTUP
script.
(Contributed by Łukasz Langa in gh-131507.)
Binary releases for the experimental just-in-time compiler¶
The official macOS and Windows release binaries now include an experimental
just-in-time (JIT) compiler. Although it is not recommended for production
use, it can be tested by setting PYTHON_JIT=1
as an
environment variable. Downstream source builds and redistributors can use the
--enable-experimental-jit=yes-off
configuration option for similar
behavior.
The JIT is at an early stage and still in active development. As such, the
typical performance impact of enabling it can range from 10% slower to 20%
faster, depending on workload. To aid in testing and evaluation, a set of
introspection functions has been provided in the sys._jit
namespace.
sys._jit.is_available()
can be used to determine if the current executable
supports JIT compilation, while sys._jit.is_enabled()
can be used to tell
if JIT compilation has been enabled for the current process.
Currently, the most significant missing functionality is that native debuggers
and profilers like gdb
and perf
are unable to unwind through JIT frames
(Python debuggers and profilers, like pdb
or profile
, continue to
work without modification). Free-threaded builds do not support JIT compilation.
Please report any bugs or major performance regressions that you encounter!
Ver também
Other language changes¶
The default interactive shell now supports import autocompletion. This means that typing
import foo
and pressing<tab>
will suggest modules starting withfoo
. Similarly, typingfrom foo import b
will suggest submodules offoo
starting withb
. Note that autocompletion of module attributes is not currently supported. (Contributed by Tomas Roun in gh-69605.)The
map()
built-in now has an optional keyword-only strict flag likezip()
to check that all the iterables are of equal length. (Contributed by Wannes Boeykens in gh-119793.)Incorrect usage of
await
and asynchronous comprehensions is now detected even if the code is optimized away by the-O
command-line option. For example,python -O -c 'assert await 1'
now produces aSyntaxError
. (Contributed by Jelle Zijlstra in gh-121637.)Writes to
__debug__
are now detected even if the code is optimized away by the-O
command-line option. For example,python -O -c 'assert (__debug__ := 1)'
now produces aSyntaxError
. (Contributed by Irit Katriel in gh-122245.)Add class methods
float.from_number()
andcomplex.from_number()
to convert a number tofloat
orcomplex
type correspondingly. They raise an error if the argument is a string. (Contributed by Serhiy Storchaka in gh-84978.)Implement mixed-mode arithmetic rules combining real and complex numbers as specified by C standards since C99. (Contributed by Sergey B Kirpichev in gh-69639.)
All Windows code pages are now supported as “cpXXX” codecs on Windows. (Contributed by Serhiy Storchaka in gh-123803.)
super
objects are nowpickleable
andcopyable
. (Contributed by Serhiy Storchaka in gh-125767.)The
memoryview
type now supports subscription, making it a generic type. (Contributed by Brian Schubert in gh-126012.)Support underscore and comma as thousands separators in the fractional part for floating-point presentation types of the new-style string formatting (with
format()
or Literais de strings formatadas). (Contributed by Sergey B Kirpichev in gh-87790.)The
bytes.fromhex()
andbytearray.fromhex()
methods now accept ASCIIbytes
and bytes-like objects. (Contributed by Daniel Pope in gh-129349.)Support
\z
as a synonym for\Z
inregular expressions
. It is interpreted unambiguously in many other regular expression engines, unlike\Z
, which has subtly different behavior. (Contributed by Serhiy Storchaka in gh-133306.)\B
inregular expression
now matches empty input string. Now it is always the opposite of\b
. (Contributed by Serhiy Storchaka in gh-124130.)iOS and macOS apps can now be configured to redirect
stdout
andstderr
content to the system log. (Contributed by Russell Keith-Magee in gh-127592.)The iOS testbed is now able to stream test output while the test is running. The testbed can also be used to run the test suite of projects other than CPython itself. (Contributed by Russell Keith-Magee in gh-127592.)
Three-argument
pow()
now tries calling__rpow__()
if necessary. Previously it was only called in two-argumentpow()
and the binary power operator. (Contributed by Serhiy Storchaka in gh-130104.)Add a built-in implementation for HMAC (RFC 2104) using formally verified code from the HACL* project. This implementation is used as a fallback when the OpenSSL implementation of HMAC is not available. (Contributed by Bénédikt Tran in gh-99108.)
The import time flag can now track modules that are already loaded (‘cached’), via the new
-X importtime=2
. When such a module is imported, theself
andcumulative
times are replaced by the stringcached
. Values above2
for-X importtime
are now reserved for future use. (Contributed by Noah Kim and Adam Turner in gh-118655.)When subclassing from a pure C type, the C slots for the new type are no longer replaced with a wrapped version on class creation if they are not explicitly overridden in the subclass. (Contributed by Tomasz Pytel in gh-132329.)
The command-line option
-c
now automatically dedents its code argument before execution. The auto-dedentation behavior mirrorstextwrap.dedent()
. (Contributed by Jon Crall and Steven Sun in gh-103998.)Improve error message when an object supporting the synchronous context manager protocol is entered using
async with
instead ofwith
. And vice versa with the asynchronous context manager protocol. (Contributed by Bénédikt Tran in gh-128398.)-J
is no longer a reserved flag for Jython, and now has no special meaning. (Contributed by Adam Turner in gh-133336.)
PEP 765: Disallow return
/break
/continue
that exit a finally
block¶
The compiler emits a SyntaxWarning
when a return
, break
or
continue
statements appears where it exits a finally
block.
This change is specified in PEP 765.
Novos módulos¶
annotationlib
: For introspecting annotations. See PEP 749 for more details. (Contributed by Jelle Zijlstra in gh-119180.)
Improved modules¶
argparse¶
The default value of the program name for
argparse.ArgumentParser
now reflects the way the Python interpreter was instructed to find the__main__
module code. (Contributed by Serhiy Storchaka and Alyssa Coghlan in gh-66436.)Introduced the optional suggest_on_error parameter to
argparse.ArgumentParser
, enabling suggestions for argument choices and subparser names if mistyped by the user. (Contributed by Savannah Ostrowski in gh-124456.)Introduced the optional color parameter to
argparse.ArgumentParser
, enabling color for help text. This can be controlled by environment variables. Color has also been enabled for help in the stdlib CLIs which useargparse
. (Contributed by Hugo van Kemenade in gh-130645.)
ast¶
Add
ast.compare()
for comparing two ASTs. (Contributed by Batuhan Taskaya and Jeremy Hylton in gh-60191.)Add support for
copy.replace()
for AST nodes. (Contributed by Bénédikt Tran in gh-121141.)Docstrings are now removed from an optimized AST in optimization level 2. (Contributed by Irit Katriel in gh-123958.)
The
repr()
output for AST nodes now includes more information. (Contributed by Tomas Roun in gh-116022.)ast.parse()
, when called with an AST as input, now always verifies that the root node type is appropriate. (Contributed by Irit Katriel in gh-130139.)Add new
--feature-version
,--optimize
,--show-empty
options to command-line interface. (Contributed by Semyon Moroz in gh-133367.)
asyncio¶
The function and methods named
create_task()
now take an arbitrary list of keyword arguments. All keyword arguments are passed to theTask
constructor or the custom task factory. (Seeset_task_factory()
for details.) Thename
andcontext
keyword arguments are no longer special; the name should now be set using thename
keyword argument of the factory, andcontext
may beNone
.Isso afeta as seguintes funções e métodos:
asyncio.create_task()
,asyncio.loop.create_task()
,asyncio.TaskGroup.create_task()
. (Contribuição de Thomas Grainger em gh-128307.)
bdb¶
The
bdb
module now supports thesys.monitoring
backend. (Contributed by Tian Gao in gh-124533.)
calendar¶
By default, today’s date is highlighted in color in
calendar
’s command-line text output. This can be controlled by environment variables. (Contributed by Hugo van Kemenade in gh-128317.)
concurrent.futures¶
Add
InterpreterPoolExecutor
, which exposes “subinterpreters” (multiple Python interpreters in the same process) to Python code. This is separate from the proposed API in PEP 734. (Contributed by Eric Snow in gh-124548.)
The default
ProcessPoolExecutor
start method changed from fork to forkserver on platforms other than macOS and Windows where it was already spawn.If the threading incompatible fork method is required, you must explicitly request it by supplying a multiprocessing context mp_context to
ProcessPoolExecutor
.See forkserver restrictions for information and differences with the fork method and how this change may affect existing code with mutable global shared variables and/or shared objects that can not be automatically
pickled
.(Contributed by Gregory P. Smith in gh-84559.)
Add
concurrent.futures.ProcessPoolExecutor.terminate_workers()
andconcurrent.futures.ProcessPoolExecutor.kill_workers()
as ways to terminate or kill all living worker processes in the given pool. (Contributed by Charles Machalow in gh-130849.)Add the optional
buffersize
parameter toconcurrent.futures.Executor.map()
to limit the number of submitted tasks whose results have not yet been yielded. If the buffer is full, iteration over the iterables pauses until a result is yielded from the buffer. (Contributed by Enzo Bonnal and Josh Rosenberg in gh-74028.)
configparser¶
Security fix: will no longer write config files it cannot read. Attempting to
configparser.ConfigParser.write()
keys containing delimiters or beginning with the section header pattern will raise aconfigparser.InvalidWriteError
. (Contributed by Jacob Lincoln in gh-129270.)
contextvars¶
Support context manager protocol by
contextvars.Token
. (Contributed by Andrew Svetlov in gh-129889.)
ctypes¶
The layout of bit fields in
Structure
andUnion
now matches platform defaults (GCC/Clang or MSVC) more closely. In particular, fields no longer overlap. (Contributed by Matthias Görgens in gh-97702.)The
Structure._layout_
class attribute can now be set to help match a non-default ABI. (Contributed by Petr Viktorin in gh-97702.)The class of
Structure
/Union
field descriptors is now available asCField
, and has new attributes to aid debugging and introspection. (Contributed by Petr Viktorin in gh-128715.)On Windows, the
COMError
exception is now public. (Contributed by Jun Komoda in gh-126686.)On Windows, the
CopyComPointer()
function is now public. (Contributed by Jun Komoda in gh-127275.)ctypes.memoryview_at()
now exists to create amemoryview
object that refers to the supplied pointer and length. This works likectypes.string_at()
except it avoids a buffer copy, and is typically useful when implementing pure Python callback functions that are passed dynamically-sized buffers. (Contributed by Rian Hunter in gh-112018.)Complex types,
c_float_complex
,c_double_complex
andc_longdouble_complex
, are now available if both the compiler and thelibffi
library support complex C types. (Contributed by Sergey B Kirpichev in gh-61103.)Add
ctypes.util.dllist()
for listing the shared libraries loaded by the current process. (Contributed by Brian Ward in gh-119349.)Move
ctypes.POINTER()
types cache from a global internal cache (_pointer_type_cache
) to thectypes._CData.__pointer_type__
attribute of the correspondingctypes
types. This will stop the cache from growing without limits in some situations. (Contributed by Sergey Miryanov in gh-100926.)The
ctypes.py_object
type now supports subscription, making it a generic type. (Contributed by Brian Schubert in gh-132168.)ctypes
now supports free-threading builds. (Contributed by Kumar Aditya and Peter Bierma in gh-127945.)
curses¶
Add the
assume_default_colors()
function, a refinement of theuse_default_colors()
function which allows to change the color pair0
. (Contributed by Serhiy Storchaka in gh-133139.)
datetime¶
Add
datetime.time.strptime()
anddatetime.date.strptime()
. (Contributed by Wannes Boeykens in gh-41431.)
decimal¶
Add alternative
Decimal
constructorDecimal.from_number()
. (Contributed by Serhiy Storchaka in gh-121798.)Expose
decimal.IEEEContext()
to support creation of contexts corresponding to the IEEE 754 (2008) decimal interchange formats. (Contributed by Sergey B Kirpichev in gh-53032.)
difflib¶
Comparison pages with highlighted changes generated by the
difflib.HtmlDiff
class now support dark mode. (Contributed by Jiahao Li in gh-129939.)
dis¶
Add support for rendering full source location information of
instructions
, rather than only the line number. This feature is added to the following interfaces via the show_positions keyword argument:This feature is also exposed via
dis --show-positions
. (Contributed by Bénédikt Tran in gh-123165.)Add the
dis --specialized
command-line option to show specialized bytecode. (Contributed by Bénédikt Tran in gh-127413.)
errno¶
Add
errno.EHWPOISON
error code. (Contributed by James Roy in gh-126585.)
faulthandler¶
Add support for printing the C stack trace on systems that support it via
faulthandler.dump_c_stack()
or via the c_stack argument infaulthandler.enable()
. (Contributed by Peter Bierma in gh-127604.)
fnmatch¶
Added
fnmatch.filterfalse()
for excluding names matching a pattern. (Contributed by Bénédikt Tran in gh-74598.)
fractions¶
Add support for converting any objects that have the
as_integer_ratio()
method to aFraction
. (Contributed by Serhiy Storchaka in gh-82017.)Add alternative
Fraction
constructorFraction.from_number()
. (Contributed by Serhiy Storchaka in gh-121797.)
functools¶
Add support to
functools.partial()
andfunctools.partialmethod()
forfunctools.Placeholder
sentinels to reserve a place for positional arguments. (Contributed by Dominykas Grigonis in gh-119127.)Allow the initial parameter of
functools.reduce()
to be passed as a keyword argument. (Contributed by Sayandip Dutta in gh-125916.)
getopt¶
getpass¶
Support keyboard feedback by
getpass.getpass()
via the keyword-only optional argumentecho_char
. Placeholder characters are rendered whenever a character is entered, and removed when a character is deleted. (Contributed by Semyon Moroz in gh-77065.)
graphlib¶
Allow
graphlib.TopologicalSorter.prepare()
to be called more than once as long as sorting has not started. (Contributed by Daniel Pope in gh-130914.)
heapq¶
Add functions for working with max-heaps:
hmac¶
http¶
Directory lists and error pages generated by the
http.server
module allow the browser to apply its default dark mode. (Contributed by Yorik Hansen in gh-123430.)The
http.server
module now supports serving over HTTPS using thehttp.server.HTTPSServer
class. This functionality is exposed by the command-line interface (python -m http.server
) through the following options:--tls-cert <path>
: Path to the TLS certificate file.--tls-key <path>
: Optional path to the private key file.--tls-password-file <path>
: Optional path to the password file for the private key.
(Contributed by Semyon Moroz in gh-85162.)
imaplib¶
Add
IMAP4.idle()
, implementing the IMAP4IDLE
command as defined in RFC 2177. (Contributed by Forest in gh-55454.)
inspect¶
inspect.signature()
takes a new argument annotation_format to control theannotationlib.Format
used for representing annotations. (Contributed by Jelle Zijlstra in gh-101552.)inspect.Signature.format()
takes a new argument unquote_annotations. If true, string annotations are displayed without surrounding quotes. (Contributed by Jelle Zijlstra in gh-101552.)Add function
inspect.ispackage()
to determine whether an object is a package or not. (Contributed by Zhikang Yan in gh-125634.)
io¶
Reading text from a non-blocking stream with
read
may now raise aBlockingIOError
if the operation cannot immediately return bytes. (Contributed by Giovanni Siragusa in gh-109523.)Add protocols
io.Reader
andio.Writer
as a simpler alternatives to the pseudo-protocolstyping.IO
,typing.TextIO
, andtyping.BinaryIO
. (Contributed by Sebastian Rittau in gh-127648.)
json¶
Add notes for JSON serialization errors that allow to identify the source of the error. (Contributed by Serhiy Storchaka in gh-122163.)
Enable the
json
module to work as a script using the-m
switch: python -m json. See the JSON command-line interface documentation. (Contributed by Trey Hunner in gh-122873.)By default, the output of the JSON command-line interface is highlighted in color. This can be controlled by environment variables. (Contributed by Tomas Roun in gh-131952.)
linecache¶
linecache.getline()
can retrieve source code for frozen modules. (Contributed by Tian Gao in gh-131638.)
logging.handlers¶
logging.handlers.QueueListener
now implements the context manager protocol, allowing it to be used in awith
statement. (Contributed by Charles Machalow in gh-132106.)QueueListener.start
now raises aRuntimeError
if the listener is already started. (Contributed by Charles Machalow in gh-132106.)
math¶
Added more detailed error messages for domain errors in the module. (Contributed by by Charlie Zhao and Sergey B Kirpichev in gh-101410.)
mimetypes¶
Document the command-line for
mimetypes
. It now exits with1
on failure instead of0
and2
on incorrect command-line parameters instead of1
. Also, errors are printed to stderr instead of stdout and their text is made tighter. (Contributed by Oleg Iarygin and Hugo van Kemenade in gh-93096.)Add MS and RFC 8081 MIME types for fonts:
Embedded OpenType:
application/vnd.ms-fontobject
OpenType Layout (OTF)
font/otf
TrueType:
font/ttf
WOFF 1.0
font/woff
WOFF 2.0
font/woff2
(Contributed by Sahil Prajapati and Hugo van Kemenade in gh-84852.)
Add RFC 9559 MIME types for Matroska audiovisual data container structures, containing:
audio with no video:
audio/matroska
(.mka
)video:
video/matroska
(.mkv
)stereoscopic video:
video/matroska-3d
(.mk3d
)
(Contributed by Hugo van Kemenade in gh-89416.)
Add MIME types for images with RFCs:
RFC 1494: CCITT Group 3 (
.g3
)RFC 3362: Real-time Facsimile, T.38 (
.t38
)RFC 3745: JPEG 2000 (
.jp2
), extension (.jpx
) and compound (.jpm
)RFC 3950: Tag Image File Format Fax eXtended, TIFF-FX (
.tfx
)RFC 4047: Flexible Image Transport System (
.fits
)RFC 7903: Enhanced Metafile (
.emf
) and Windows Metafile (.wmf
)
(Contributed by Hugo van Kemenade in gh-85957.)
More MIME type changes:
RFC 2361: Change type for
.avi
tovideo/vnd.avi
and for.wav
toaudio/vnd.wave
RFC 4337: Add MPEG-4
audio/mp4
(.m4a
)RFC 5334: Add Ogg media (
.oga
,.ogg
and.ogx
)RFC 6713: Add gzip
application/gzip
(.gz
)RFC 9639: Add FLAC
audio/flac
(.flac
)Add 7z
application/x-7z-compressed
(.7z
)Add Android Package
application/vnd.android.package-archive
(.apk
) when not strictAdd deb
application/x-debian-package
(.deb
)Add glTF binary
model/gltf-binary
(.glb
)Add glTF JSON/ASCII
model/gltf+json
(.gltf
)Add M4V
video/x-m4v
(.m4v
)Add PHP
application/x-httpd-php
(.php
)Add RAR
application/vnd.rar
(.rar
)Add RPM
application/x-rpm
(.rpm
)Add STL
model/stl
(.stl
)Add Windows Media Video
video/x-ms-wmv
(.wmv
)De facto: Add WebM
audio/webm
(.weba
)ECMA-376: Add
.docx
,.pptx
and.xlsx
typesOASIS: Add OpenDocument
.odg
,.odp
,.ods
and.odt
typesW3C: Add EPUB
application/epub+zip
(.epub
)
(Contributed by Hugo van Kemenade in gh-129965.)
Add RFC 9512
application/yaml
MIME type for YAML files (.yaml
and.yml
). (Contributed by Sasha “Nelie” Chernykh and Hugo van Kemenade in gh-132056.)
multiprocessing¶
The default start method changed from fork to forkserver on platforms other than macOS and Windows where it was already spawn.
If the threading incompatible fork method is required, you must explicitly request it via a context from
multiprocessing.get_context()
(preferred) or change the default viamultiprocessing.set_start_method()
.See forkserver restrictions for information and differences with the fork method and how this change may affect existing code with mutable global shared variables and/or shared objects that can not be automatically
pickled
.(Contributed by Gregory P. Smith in gh-84559.)
multiprocessing
’s"forkserver"
start method now authenticates its control socket to avoid solely relying on filesystem permissions to restrict what other processes could cause the forkserver to spawn workers and run code. (Contributed by Gregory P. Smith for gh-97514.)The multiprocessing proxy objects for list and dict types gain previously overlooked missing methods:
clear()
andcopy()
for proxies oflist
fromkeys()
,reversed(d)
,d | {}
,{} | d
,d |= {'b': 2}
for proxies ofdict
(Contributed by Roy Hyunjin Han for gh-103134.)
Add support for shared
set
objects viaSyncManager.set()
. Theset()
inmultiprocessing.Manager()
method is now available. (Contributed by Mingyu Park in gh-129949.)Add
multiprocessing.Process.interrupt()
which terminates the child process by sendingSIGINT
. This enablesfinally
clauses to print a stack trace for the terminated process. (Contributed by Artem Pulkin in gh-131913.)
operador¶
Two new functions
operator.is_none()
andoperator.is_not_none()
have been added, such thatoperator.is_none(obj)
is equivalent toobj is None
andoperator.is_not_none(obj)
is equivalent toobj is not None
. (Contributed by Raymond Hettinger and Nico Mexis in gh-115808.)
os¶
Add the
os.reload_environ()
function to updateos.environ
andos.environb
with changes to the environment made byos.putenv()
, byos.unsetenv()
, or made outside Python in the same process. (Contributed by Victor Stinner in gh-120057.)Add the
SCHED_DEADLINE
andSCHED_NORMAL
constants to theos
module. (Contributed by James Roy in gh-127688.)Add the
os.readinto()
function to read into a buffer object from a file descriptor. (Contributed by Cody Maloney in gh-129205.)
os.path¶
The strict parameter to
os.path.realpath()
accepts a new value,os.path.ALLOW_MISSING
. If used, errors other thanFileNotFoundError
will be re-raised; the resulting path can be missing but it will be free of symlinks. (Contributed by Petr Viktorin for CVE 2025-4517.)
pathlib¶
Add methods to
pathlib.Path
to recursively copy or move files and directories:copy()
copies a file or directory tree to a destination.copy_into()
copies into a destination directory.move()
moves a file or directory tree to a destination.move_into()
moves into a destination directory.
(Contributed by Barney Gale in gh-73991.)
Add
pathlib.Path.info
attribute, which stores an object implementing thepathlib.types.PathInfo
protocol (also new). The object supports querying the file type and internally cachingstat()
results. Path objects generated byiterdir()
are initialized with file type information gleaned from scanning the parent directory. (Contributed by Barney Gale in gh-125413.)
pdb¶
Hardcoded breakpoints (
breakpoint()
andpdb.set_trace()
) now reuse the most recentPdb
instance that callsset_trace()
, instead of creating a new one each time. As a result, all the instance specific data likedisplay
andcommands
are preserved across hardcoded breakpoints. (Contributed by Tian Gao in gh-121450.)Add a new argument mode to
pdb.Pdb
. Disable therestart
command whenpdb
is ininline
mode. (Contributed by Tian Gao in gh-123757.)A confirmation prompt will be shown when the user tries to quit
pdb
ininline
mode.y
,Y
,<Enter>
orEOF
will confirm the quit and callsys.exit()
, instead of raisingbdb.BdbQuit
. (Contributed by Tian Gao in gh-124704.)Inline breakpoints like
breakpoint()
orpdb.set_trace()
will always stop the program at calling frame, ignoring theskip
pattern (if any). (Contributed by Tian Gao in gh-130493.)<tab>
at the beginning of the line inpdb
multi-line input will fill in a 4-space indentation now, instead of inserting a\t
character. (Contributed by Tian Gao in gh-130471.)Auto-indent is introduced in
pdb
multi-line input. It will either keep the indentation of the last line or insert a 4-space indentation when it detects a new code block. (Contributed by Tian Gao in gh-133350.)$_asynctask
is added to access the current asyncio task if applicable. (Contributed by Tian Gao in gh-124367.)pdb
now supports two backends:sys.settrace()
andsys.monitoring
. Usingpdb
CLI orbreakpoint()
will always use thesys.monitoring
backend. Explicitly instantiatingpdb.Pdb
and its derived classes will use thesys.settrace()
backend by default, which is configurable. (Contributed by Tian Gao in gh-124533.)pdb.set_trace_async()
is added to support debugging asyncio coroutines.await
statements are supported with this function. (Contributed by Tian Gao in gh-132576.)Source code displayed in
pdb
will be syntax-highlighted. This feature can be controlled using the same methods as PyREPL, in addition to the newly addedcolorize
argument ofpdb.Pdb
. (Contributed by Tian Gao and Łukasz Langa in gh-133355.)
pickle¶
Set the default protocol version on the
pickle
module to 5. For more details, see pickle protocols.Add notes for pickle serialization errors that allow to identify the source of the error. (Contributed by Serhiy Storchaka in gh-122213.)
platform¶
Add
platform.invalidate_caches()
to invalidate the cached results. (Contributed by Bénédikt Tran in gh-122549.)
pydoc¶
Annotations in help output are now usually displayed in a format closer to that in the original source. (Contributed by Jelle Zijlstra in gh-101552.)
socket¶
Improve and fix support for Bluetooth sockets.
Fix support of Bluetooth sockets on NetBSD and DragonFly BSD. (Contributed by Serhiy Storchaka in gh-132429.)
Fix support for
BTPROTO_HCI
on FreeBSD. (Contributed by Victor Stinner in gh-111178.)Add support for
BTPROTO_SCO
on FreeBSD. (Contributed by Serhiy Storchaka in gh-85302.)Add support for cid and bdaddr_type in the address for
BTPROTO_L2CAP
on FreeBSD. (Contributed by Serhiy Storchaka in gh-132429.)Add support for channel in the address for
BTPROTO_HCI
on Linux. (Contributed by Serhiy Storchaka in gh-70145.)Accept an integer as the address for
BTPROTO_HCI
on Linux. (Contributed by Serhiy Storchaka in gh-132099.)Return cid in
getsockname()
forBTPROTO_L2CAP
. (Contributed by Serhiy Storchaka in gh-132429.)Add many new constants. (Contributed by Serhiy Storchaka in gh-132734.)
ssl¶
Indicate through
ssl.HAS_PHA
whether thessl
module supports TLSv1.3 post-handshake client authentication (PHA). (Contributed by Will Childs-Klein in gh-128036.)
struct¶
symtable¶
Expose the following
symtable.Symbol
methods:(Contributed by Bénédikt Tran in gh-120029.)
sys¶
A função especial
sys.getobjects()
, anteriormente não documentada, que só existe em construções especializadas do Python, agora pode retornar objetos de outros interpretadores além daquele em que foi chamada.Add
sys._is_immortal()
for determining if an object is immortal. (Contributed by Peter Bierma in gh-128509.)No FreeBSD,
sys.platform
não contém mais a versão principal. É sempre'freebsd'
, em vez de'freebsd13'
ou'freebsd14'
.Raise
DeprecationWarning
forsys._clear_type_cache()
. This function was deprecated in Python 3.13 but it didn’t raise a runtime warning.
sys.monitoring¶
Two new events are added:
BRANCH_LEFT
andBRANCH_RIGHT
. TheBRANCH
event is deprecated.
sysconfig¶
Add
ABIFLAGS
key tosysconfig.get_config_vars()
on Windows. (Contributed by Xuehai Pan in gh-131799.)
tarfile¶
data_filter()
now normalizes symbolic link targets in order to avoid path traversal attacks. (Contributed by Petr Viktorin in gh-127987 and CVE 2025-4138.)extractall()
now skips fixing up directory attributes when a directory was removed or replaced by another kind of file. (Contributed by Petr Viktorin in gh-127987 and CVE 2024-12718.)extract()
andextractall()
now (re-)apply the extraction filter when substituting a link (hard or symbolic) with a copy of another archive member, and when fixing up directory attributes. The former raises a new exception,LinkFallbackError
. (Contributed by Petr Viktorin for CVE 2025-4330 and CVE 2024-12718.)extract()
andextractall()
no longer extract rejected members whenerrorlevel()
is zero. (Contributed by Matt Prodani and Petr Viktorin in gh-112887 and CVE 2025-4435.)
threading¶
threading.Thread.start()
now sets the operating system thread name tothreading.Thread.name
. (Contributed by Victor Stinner in gh-59705.)
tkinter¶
turtle¶
Add context managers for
turtle.fill()
,turtle.poly()
andturtle.no_animation()
. (Contributed by Marie Roald and Yngve Mardal Moe in gh-126350.)
tipos¶
types.UnionType
is now an alias fortyping.Union
. See below for more details. (Contributed by Jelle Zijlstra in gh-105499.)
typing¶
types.UnionType
andtyping.Union
are now aliases for each other, meaning that both old-style unions (created withUnion[int, str]
) and new-style unions (int | str
) now create instances of the same runtime type. This unifies the behavior between the two syntaxes, but leads to some differences in behavior that may affect users who introspect types at runtime:Both syntaxes for creating a union now produce the same string representation in
repr()
. For example,repr(Union[int, str])
is now"int | str"
instead of"typing.Union[int, str]"
.Unions created using the old syntax are no longer cached. Previously, running
Union[int, str]
multiple times would return the same object (Union[int, str] is Union[int, str]
would beTrue
), but now it will return two different objects. Users should use==
to compare unions for equality, notis
. New-style unions have never been cached this way. This change could increase memory usage for some programs that use a large number of unions created by subscriptingtyping.Union
. However, several factors offset this cost: unions used in annotations are no longer evaluated by default in Python 3.14 because of PEP 649; an instance oftypes.UnionType
is itself much smaller than the object returned byUnion[]
was on prior Python versions; and removing the cache also saves some space. It is therefore unlikely that this change will cause a significant increase in memory usage for most users.Previously, 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.It is now possible to use
typing.Union
itself inisinstance()
checks. For example,isinstance(int | str, typing.Union)
will returnTrue
; previously this raisedTypeError
.The
__args__
attribute oftyping.Union
objects is no longer writable.It is no longer possible to set any attributes on
typing.Union
objects. This only ever worked for dunder attributes on previous versions, was never documented to work, and was subtly broken in many cases.
(Contributed by Jelle Zijlstra in gh-105499.)
unicodedata¶
The Unicode database has been updated to Unicode 16.0.0.
unittest¶
unittest
output is now colored by default. This can be controlled by environment variables. (Contributed by Hugo van Kemenade in gh-127221.)unittest discovery supports namespace package as start directory again. It was removed in Python 3.11. (Contributed by Jacob Walls in gh-80958.)
A number of new methods were added in the
TestCase
class that provide more specialized tests.assertHasAttr()
andassertNotHasAttr()
check whether the object has a particular attribute.assertIsSubclass()
andassertNotIsSubclass()
check whether the object is a subclass of a particular class, or of one of a tuple of classes.assertStartsWith()
,assertNotStartsWith()
,assertEndsWith()
andassertNotEndsWith()
check whether the Unicode or byte string starts or ends with particular string(s).
(Contributed by Serhiy Storchaka in gh-71339.)
urllib¶
Upgrade HTTP digest authentication algorithm for
urllib.request
by supporting SHA-256 digest authentication as specified in RFC 7616. (Contributed by Calvin Bui in gh-128193.)Improve ergonomics and standards compliance when parsing and emitting
file:
URLs.In
urllib.request.url2pathname()
:Accept a complete URL when the new require_scheme argument is set to true.
Discard URL authority if it matches the local hostname.
Discard URL authority if it resolves to a local IP address when the new resolve_host argument is set to true.
Raise
URLError
if a URL authority isn’t local, except on Windows where we return a UNC path as before.
In
urllib.request.pathname2url()
:Return a complete URL when the new add_scheme argument is set to true.
Include an empty URL authority when a path begins with a slash. For example, the path
/etc/hosts
is converted to the URL///etc/hosts
.
On Windows, drive letters are no longer converted to uppercase, and
:
characters not following a drive letter no longer cause anOSError
exception to be raised.(Contributed by Barney Gale in gh-125866.)
uuid¶
Add support for UUID versions 6, 7, and 8 via
uuid.uuid6()
,uuid.uuid7()
, anduuid.uuid8()
respectively, as specified in RFC 9562. (Contributed by Bénédikt Tran in gh-89083.)uuid.NIL
anduuid.MAX
are now available to represent the Nil and Max UUID formats as defined by RFC 9562. (Contributed by Nick Pope in gh-128427.)Allow to generate multiple UUIDs at once via
python -m uuid --count
. (Contributed by Simon Legner in gh-131236.)
webbrowser¶
Names in the
BROWSER
environment variable can now refer to already registered browsers for thewebbrowser
module, instead of always generating a new browser command.Isso torna possível definir
BROWSER
como o valor de um dos navegadores suportados no macOS.
zipinfo¶
Added
ZipInfo._for_archive
to resolve suitable defaults for aZipInfo
object as used byZipFile.writestr
. (Contributed by Bénédikt Tran in gh-123424.)zipfile.ZipFile.writestr()
now respectSOURCE_DATE_EPOCH
that distributions can set centrally and have build tools consume this in order to produce reproducible output. (Contributed by Jiahao Li in gh-91279.)
Otimizações¶
The import time for several standard library modules has been improved, including
ast
,asyncio
,base64
,cmd
,csv
,gettext
,importlib.util
,locale
,mimetypes
,optparse
,pickle
,pprint
,pstats
,socket
,subprocess
,threading
,tomllib
, andzipfile
.(Contributed by Adam Turner, Bénédikt Tran, Chris Markiewicz, Eli Schwartz, Hugo van Kemenade, Jelle Zijlstra, and others in gh-118761.)
asyncio¶
asyncio
has a new per-thread double linked list implementation internally fornative tasks
which speeds up execution by 10-20% on standard pyperformance benchmarks and reduces memory usage. This enables external introspection tools such as python -m asyncio pstree to introspect the call graph of asyncio tasks running in all threads. (Contributed by Kumar Aditya in gh-107803.)asyncio
has first class support for free-threading builds. This enables parallel execution of multiple event loops across different threads and scales linearly with the number of threads. (Contributed by Kumar Aditya in gh-128002.)asyncio
has new utility functions for introspecting and printing the program’s call graph:asyncio.capture_call_graph()
andasyncio.print_call_graph()
. (Contributed by Yury Selivanov, Pablo Galindo Salgado, and Łukasz Langa in gh-91048.)
base64¶
Improve the performance of
base64.b16decode()
by up to ten times, and reduce the import time ofbase64
by up to six times. (Contributed by Bénédikt Tran, Chris Markiewicz, and Adam Turner in gh-118761.)
io¶
io
which provides the built-inopen()
makes less system calls when opening regular files as well as reading whole files. Reading a small operating system cached file in full is up to 15% faster.pathlib.Path.read_bytes()
has the most optimizations for reading a file’s bytes in full. (Contributed by Cody Maloney and Victor Stinner in gh-120754 and gh-90102.)
uuid¶
zlib¶
On Windows,
zlib-ng
is now used as the implementation of thezlib
module. This should produce compatible and comparable results with better performance, though it is worth noting thatzlib.Z_BEST_SPEED
(1) may result in significantly less compression than the previous implementation (while also significantly reducing the time taken to compress). (Contributed by Steve Dower in gh-91349.)
Descontinuados¶
-
Passing the undocumented keyword argument prefix_chars to
add_argument_group()
is now deprecated. (Contributed by Savannah Ostrowski in gh-125563.)Deprecated the
argparse.FileType
type converter. Anything with resource management should be done downstream after the arguments are parsed. (Contributed by Serhiy Storchaka in gh-58032.)
-
asyncio.iscoroutinefunction()
foi descontinuado e será removido no Python 3.16, useinspect.iscoroutinefunction()
em vez disso. (Contribuição de Jiahao Li e Kumar Aditya em gh-122875.)O sistema de políticas
asyncio
está descontinuado e será removido no Python 3.16. Em particular, as seguintes classes e funções estão descontinuadas:Os usuários devem usar
asyncio.run()
ouasyncio.Runner
com loop_factory para usar a implementação de loop de eventos desejada.por exemplo, para usar
asyncio.SelectorEventLoop
no Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(Contribuição de Kumar Aditya em gh-127949.)
builtins
: Passing a complex number as the real or imag argument in thecomplex()
constructor is now deprecated; it should only be passed as a single positional argument. (Contributed by Serhiy Storchaka in gh-109218.)codecs
:codecs.open()
is now deprecated. Useopen()
instead. (Contributed by Inada Naoki in gh-133036.)-
On non-Windows platforms, setting
Structure._pack_
to use a MSVC-compatible default memory layout is deprecated in favor of settingStructure._layout_
to'ms'
. (Contributed by Petr Viktorin in gh-131747.)Calling
ctypes.POINTER()
on a string is deprecated. Use Tipos Incompletos for self-referential structures. Also, the internalctypes._pointer_type_cache
is deprecated. Seectypes.POINTER()
for updated implementation details. (Contributed by Sergey Myrianov in gh-100926.)
functools
: Calling the Python implementation offunctools.reduce()
with function or sequence as keyword arguments is now deprecated. (Contributed by Kirill Podoprigora in gh-121676.)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
: Valid extensions start with a ‘.’ or are empty formimetypes.MimeTypes.add_type()
. Undotted extensions are deprecated and will raise aValueError
in Python 3.16. (Contributed by Hugo van Kemenade in gh-75223.)nturl2path
: This module is now deprecated. Callurllib.request.url2pathname()
andpathname2url()
instead. (Contributed by Barney Gale in gh-125866.)os
: Soft deprecateos.popen()
andos.spawn*
functions. They should no longer be used to write new code. Thesubprocess
module is recommended instead. (Contributed by Victor Stinner in gh-120743.)pathlib
:pathlib.PurePath.as_uri()
is deprecated and will be removed in Python 3.19. Usepathlib.Path.as_uri()
instead. (Contributed by Barney Gale in gh-123599.)pdb
: The undocumentedpdb.Pdb.curframe_locals
attribute is now a deprecated read-only property. The low overhead dynamic frame locals access added in Python 3.13 by PEP 667 means the frame locals cache reference previously stored in this attribute is no longer needed. Derived debuggers should accesspdb.Pdb.curframe.f_locals
directly in Python 3.13 and later versions. (Contributed by Tian Gao in gh-124369 and gh-125951.)symtable
: Descontinuasymtable.Class.get_methods()
por falta de interesse. (Contribuição de Bénédikt Tran em gh-119698.)tkinter
: Thetkinter.Variable
methodstrace_variable()
,trace_vdelete()
andtrace_vinfo()
are now deprecated. Usetrace_add()
,trace_remove()
andtrace_info()
instead. (Contributed by Serhiy Storchaka in gh-120220.)urllib.parse
: Accepting objects with false values (like0
and[]
) except empty strings, byte-like objects andNone
inurllib.parse
functionsparse_qsl()
andparse_qs()
is now deprecated. (Contributed by Serhiy Storchaka in gh-116897.)
Remoção pendente no Python 3.15¶
O sistema de importação:
A definição de
__cached__
em um módulo enquanto falha na definição de__spec__.cached
está descontinuado. No Python 3.15,__cached__
deixará de ser definido ou levado em consideração pelo sistema de importação ou pela biblioteca padrão. (gh-97879)A definição de
__package__
em um módulo enquanto falha na definição de__spec__.parent
está descontinuado. No Python 3.15,__package__
deixará de ser definido ou levado em consideração pelo sistema de importação ou pela biblioteca padrão. (gh-97879)
-
A função não documentada
ctypes.SetPointerType()
foi descontinuada desde o Python 3.13.
-
A classe obsoleta e raramente usada
CGIHTTPRequestHandler
foi descontinuada desde o Python 3.13. Não existe substituição direta. Qualquer coisa é melhor que CGI para fazer a interface de um servidor web com um manipulador de requisição.O sinalizador
--cgi
para a interface de linha de comando python -m http.server foi descontinuado desde o Python 3.13.
-
Método
load_module()
: useexec_module()
.
-
A função
getdefaultlocale()
foi descontinuada desde o Python 3.11. Sua remoção foi planejada originalmente para o Python 3.13 (gh-90817), mas foi adiada para o Python 3.15. Em vez disso, usegetlocale()
,setlocale()
egetencoding()
. (Contribuição de Hugo van Kemenade em gh-111187.)
-
PurePath.is_reserved()
foi descontinuado desde o Python 3.13. Useos.path.isreserved()
para detectar caminhos reservados no Windows.
-
java_ver()
foi descontinuada desde o Python 3.13. Esta função é útil apenas para suporte Jython, tem uma API confusa e é amplamente não testada.
-
O argumento check_home de
sysconfig.is_python_build()
foi descontinuado desde o Python 3.12.
-
RLock()
não aceitará argumentos no Python 3.15. A passagem quaisquer argumentos foi descontinuada desde o Python 3.14, pois a versão Python não permite nenhum argumento, mas a versão C permite qualquer número de argumentos posicionais ou nomeados, ignorando todos os argumentos.
-
types.CodeType
: o acesso aco_lnotab
foi descontinuado na PEP 626 desde 3.10 e foi planejado para ser removido em 3.12, mas só recebeu umaDeprecationWarning
adequada em 3.12. Pode ser removido em 3.15. (Contribuição de Nikita Sobolev em gh-101866.)
-
A não-documentada sintaxe de argumento nomeado para criar classes
NamedTuple
(por exemplo,Point = NamedTuple("Point", x=int, y=int)
) foi descontinuada desde o Python 3.13. Em vez disso, use as sintaxes baseada em classe ou funcional.Ao usar a sintaxe funcional de
TypedDict
s, não passar um valor para o parâmetro fields (TD = TypedDict("TD")
) ou passarNone
(TD = TypedDict("TD", None)
) foi está descontinuado desde o Python 3.13. Useclass TD(TypedDict): pass
ouTD = TypedDict("TD", {})
para criar uma classe TypedDict com nenhum campo.A função decoradora
typing.no_type_check_decorator()
foi descontinuada desde o Python 3.13. Após oito anos no módulotyping
, ela ainda não foi suportada por nenhum verificador de tipo importante.
wave
:Os métodos
getmark()
,setmark()
egetmarkers()
das classesWave_read
eWave_write
foram descontinuados desde o Python 3.13.
-
load_module()
está descontinuado desde o Python 3.10. Em vez disso, useexec_module()
. (Contribuição de Jiahao Li em gh-125746.)
Remoção pendente no Python 3.16¶
O sistema de importação:
A definição de
__loader__
em um módulo enquanto falha na definição de__spec__.loader
está descontinuado. No Python 3.16,__loader__
deixará de ser definido ou levado em consideração pelo sistema de importação ou pela biblioteca padrão.
-
O código de formato
'u'
(wchar_t
) foi descontinuado na documentação desde o Python 3.3 e do ambiente de execução desde o Python 3.13. Em vez disso, use o código de formato'w'
(Py_UCS4
) para caracteres Unicode.
-
asyncio.iscoroutinefunction()
foi descontinuado e será removido no Python 3.16, useinspect.iscoroutinefunction()
em vez disso. (Contribuição de Jiahao Li e Kumar Aditya em gh-122875.)O sistema de políticas
asyncio
está descontinuado e será removido no Python 3.16. Em particular, as seguintes classes e funções estão descontinuadas:Os usuários devem usar
asyncio.run()
ouasyncio.Runner
com loop_factory para usar a implementação de loop de eventos desejada.por exemplo, para usar
asyncio.SelectorEventLoop
no Windows:import asyncio async def main(): ... asyncio.run(main(), loop_factory=asyncio.SelectorEventLoop)
(Contribuição de Kumar Aditya em gh-127949.)
-
A inversão bit a bit em tipos booleanos,
~True
ou~False
foi descontinuada desde o Python 3.12, pois produz resultados surpreendentes e não intuitivos (-2
e-1
). Em vez disso, usenot x
para a negação lógica de um booleano. No caso raro de você precisar da inversão bit a bit do inteiro subjacente, converta paraint
explicitamente (~int(x)
).
-
A chamada da implementação Python de
functools.reduce()
com function ou sequence como argumentos nomeados foi descontinuada desde o Python 3.14.
-
O suporte para manipuladores de registro personalizados com o argumento strm foi descontinuado e está programado para ser removido no Python 3.16. Em vez disso, defina manipuladores com o argumento stream. (Contribuição de Mariusz Felisiak em gh-115032.)
-
Extensões válidas começam com um ‘.’ ou estão vazias para
mimetypes.MimeTypes.add_type()
. Extensões sem ponto estão descontinuadas e levantarão uma exceçãoValueError
no Python 3.16. (Contribuição de Hugo van Kemenade em gh-75223.)
-
A exceção
ExecError
foi descontinuada desde o Python 3.14. Ela não foi usada por nenhuma função emshutil
desde o Python 3.4, e agora é um alias deRuntimeError
.
-
O método
Class.get_methods
foi descontinuado desde o Python 3.14.
sys
:A função
_enablelegacywindowsfsencoding()
foi descontinuada desde o Python 3.13. Em vez disso, use a variável de ambientePYTHONLEGACYWINDOWSFSENCODING
.
-
A função
sysconfig.expand_makefile_vars()
está descontinuada desde o Python 3.14. Em vez disso, use o argumentovars
desysconfig.get_paths()
.
-
O atributo não documentado e não utilizado
TarFile.tarfile
foi descontinuado desde o Python 3.13.
Remoção pendente no Python 3.17¶
-
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.
Remoção pendente no Python 3.19¶
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.FileType
está descontinuado.
-
bool(NotImplemented)
.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
,is
eor
. 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
.Delegação do método
int()
para o__trunc__()
.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.January
ecalendar.February
foram descontinuadas e substituídas porcalendar.JANUARY
ecalendar.FEBRUARY
. (Contribuição de Prince Roshan em gh-103636.)codecs
: useopen()
em vez decodecs.open()
. (gh-133038)codeobject.co_lnotab
: use o métodocodeobject.co_lines()
.-
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: use o parâmetro optimization.
-
Interface de tupla
EntryPoints
.None
implí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
: chameos.register_at_fork()
em processo multithread.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.)Módulos
sre_compile
,sre_constants
esre_parse
.shutil
: o parâmetro onerror dermtree()
foi descontinuado no Python 3.12; use o parâmetro onexc.Protocolos e opções de
ssl
ssl.SSLContext
sem 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_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 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._UnionGenericAlias
nã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 sejaNone
de 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 umElement
está 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()
.
Removidos¶
argparse¶
Remove the type, choices, and metavar parameters of
argparse.BooleanOptionalAction
. They were deprecated since 3.12.Calling
add_argument_group()
on an argument group, and callingadd_argument_group()
oradd_mutually_exclusive_group()
on a mutually exclusive group now raise exceptions. This nesting was never supported, often failed to work correctly, and was unintentionally exposed through inheritance. This functionality has been deprecated since Python 3.11. (Contributed by Savannah Ostrowski in gh-127186.)
ast¶
Remove the following classes. They were all deprecated since Python 3.8, and have emitted deprecation warnings since Python 3.12:
ast.Bytes
ast.Ellipsis
ast.NameConstant
ast.Num
ast.Str
Use
ast.Constant
instead. As a consequence of these removals, user-definedvisit_Num
,visit_Str
,visit_Bytes
,visit_NameConstant
andvisit_Ellipsis
methods on customast.NodeVisitor
subclasses will no longer be called when theNodeVisitor
subclass is visiting an AST. Define avisit_Constant
method instead.Also, remove the following deprecated properties on
ast.Constant
, which were present for compatibility with the now-removed AST classes:ast.Constant.n
ast.Constant.s
Use
ast.Constant.value
instead. (Contributed by Alex Waygood in gh-119562.)
asyncio¶
Remove the following classes and functions. They were all deprecated and emitted deprecation warnings since Python 3.12:
asyncio.get_child_watcher()
asyncio.set_child_watcher()
asyncio.AbstractEventLoopPolicy.get_child_watcher()
asyncio.AbstractEventLoopPolicy.set_child_watcher()
asyncio.AbstractChildWatcher
asyncio.FastChildWatcher
asyncio.MultiLoopChildWatcher
asyncio.PidfdChildWatcher
asyncio.SafeChildWatcher
asyncio.ThreadedChildWatcher
(Contributed by Kumar Aditya in gh-120804.)
Removed implicit creation of event loop by
asyncio.get_event_loop()
. It now raises aRuntimeError
if there is no current event loop. (Contributed by Kumar Aditya in gh-126353.)There’s a few patterns that use
asyncio.get_event_loop()
, most of them can be replaced withasyncio.run()
.If you’re running an async function, simply use
asyncio.run()
.Before:
async def main(): ... loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) finally: loop.close()
After:
async def main(): ... asyncio.run(main())
If you need to start something, for example, a server listening on a socket and then run forever, use
asyncio.run()
and anasyncio.Event
.Before:
def start_server(loop): ... loop = asyncio.get_event_loop() try: start_server(loop) loop.run_forever() finally: loop.close()
After:
def start_server(loop): ... async def main(): start_server(asyncio.get_running_loop()) await asyncio.Event().wait() asyncio.run(main())
If you need to run something in an event loop, then run some blocking code around it, use
asyncio.Runner
.Before:
async def operation_one(): ... def blocking_code(): ... async def operation_two(): ... loop = asyncio.get_event_loop() try: loop.run_until_complete(operation_one()) blocking_code() loop.run_until_complete(operation_two()) finally: loop.close()
After:
async def operation_one(): ... def blocking_code(): ... async def operation_two(): ... with asyncio.Runner() as runner: runner.run(operation_one()) blocking_code() runner.run(operation_two())
collections.abc¶
Remove
collections.abc.ByteString
. It had previously raised aDeprecationWarning
since Python 3.12.
email¶
Remove the isdst parameter from
email.utils.localtime()
. (Contributed by Hugo van Kemenade in gh-118798.)
importlib¶
Remove deprecated
importlib.abc
classes:importlib.abc.ResourceReader
importlib.abc.Traversable
importlib.abc.TraversableResources
Em vez disso, use classes de
importlib.resources.abc
:(Contribuição de Jason R. Coombs e Hugo van Kemenade em gh-93963.)
itertools¶
Remove
itertools
support for copy, deepcopy, and pickle operations. These had previously raised aDeprecationWarning
since Python 3.12. (Contributed by Raymond Hettinger in gh-101588.)
pathlib¶
Remove support for passing additional keyword arguments to
pathlib.Path
. In previous versions, any such arguments are ignored.Remove support for passing additional positional arguments to
pathlib.PurePath.relative_to()
andis_relative_to()
. In previous versions, any such arguments are joined onto other.
pkgutil¶
Remove deprecated
pkgutil.get_loader()
andpkgutil.find_loader()
. These had previously raised aDeprecationWarning
since Python 3.12. (Contributed by Bénédikt Tran in gh-97850.)
pty¶
Remove deprecated
pty.master_open()
andpty.slave_open()
. They had previously raised aDeprecationWarning
since Python 3.12. Usepty.openpty()
instead. (Contributed by Nikita Sobolev in gh-118824.)
sqlite3¶
Remove
version
andversion_info
fromsqlite3
. (Contributed by Hugo van Kemenade in gh-118924.)Disallow using a sequence of parameters with named placeholders. This had previously raised a
DeprecationWarning
since Python 3.12; it will now raise asqlite3.ProgrammingError
. (Contributed by Erlend E. Aasland in gh-118928 and gh-101693.)
typing¶
Remove
typing.ByteString
. It had previously raised aDeprecationWarning
since Python 3.12.typing.TypeAliasType
now supports star unpacking.
urllib¶
Remove deprecated
Quoter
class fromurllib.parse
. It had previously raised aDeprecationWarning
since Python 3.11. (Contributed by Nikita Sobolev in gh-118827.)Remove deprecated
URLopener
andFancyURLopener
classes fromurllib.request
. They had previously raised aDeprecationWarning
since Python 3.3.myopener.open()
can be replaced withurlopen()
, andmyopener.retrieve()
can be replaced withurlretrieve()
. Customizations to the opener classes can be replaced by passing customized handlers tobuild_opener()
. (Contributed by Barney Gale in gh-84850.)
Outros¶
Using
NotImplemented
in a boolean context will now raise aTypeError
. It had previously raised aDeprecationWarning
since Python 3.9. (Contributed by Jelle Zijlstra in gh-118767.)The
int()
built-in no longer delegates to__trunc__()
. Classes that want to support conversion to integer must implement either__int__()
or__index__()
. (Contributed by Mark Dickinson in gh-119743.)
Alterações de bytecode do CPython¶
Porting to Python 3.14¶
Esta seção lista as alterações descritas anteriormente e outras correções que podem exigir alterações no seu código.
Alterações na API Python¶
functools.partial
is now a method descriptor. Wrap it instaticmethod()
if you want to preserve the old behavior. (Contributed by Serhiy Storchaka and Dominykas Grigonis in gh-121027.)The
locale.nl_langinfo()
function now sets temporarily theLC_CTYPE
locale in some cases. This temporary change affects other threads. (Contributed by Serhiy Storchaka in gh-69998.)types.UnionType
is now an alias fortyping.Union
, causing changes in some behaviors. See above for more details. (Contributed by Jelle Zijlstra in gh-105499.)The runtime behavior of annotations has changed in various ways; see above for details. While most code that interacts with annotations should continue to work, some undocumented details may behave differently.
Build changes¶
GNU Autoconf 2.72 is now required to generate
configure
. (Contributed by Erlend Aasland in gh-115765.)#pragma
-based linking withpython3*.lib
can now be switched off with Py_NO_LINK_LIB. (Contributed by Jean-Christophe Fillion-Robin in gh-82909.)
PEP 761: Discontinuation of PGP signatures¶
PGP signatures will not be available for CPython 3.14 and onwards. Users verifying artifacts must use Sigstore verification materials for verifying CPython artifacts. This change in release process is specified in PEP 761.
C API changes¶
Novas funcionalidades¶
Add
PyLong_GetSign()
function to get the sign ofint
objects. (Contributed by Sergey B Kirpichev in gh-116560.)Add a new
PyUnicodeWriter
API to create a Pythonstr
object:(Contributed by Victor Stinner in gh-119182.)
Add
PyIter_NextItem()
to replacePyIter_Next()
, which has an ambiguous return value. (Contributed by Irit Katriel and Erlend Aasland in gh-105201.)Add
PyLong_IsPositive()
,PyLong_IsNegative()
andPyLong_IsZero()
for checking ifPyLongObject
is positive, negative, or zero, respectively. (Contributed by James Roy and Sergey B Kirpichev in gh-126061.)Add new functions to convert C
<stdint.h>
numbers from/to Pythonint
:(Contributed by Victor Stinner in gh-120389.)
Add
PyBytes_Join(sep, iterable)
function, similar tosep.join(iterable)
in Python. (Contributed by Victor Stinner in gh-121645.)Add
Py_HashBuffer()
to compute and return the hash value of a buffer. (Contributed by Antoine Pitrou and Victor Stinner in gh-122854.)Add functions to get and set the current runtime Python configuration (PEP 741):
(Contribuição de Victor Stinner em gh-107954.)
Add functions to configure the Python initialization (PEP 741):
(Contribuição de Victor Stinner em gh-107954.)
Add a new import and export API for Python
int
objects (PEP 757):(Contributed by Sergey B Kirpichev and Victor Stinner in gh-102471.)
Add
PyType_GetBaseByToken()
andPy_tp_token
slot for easier superclass identification, which attempts to resolve the type checking issue mentioned in PEP 630. (Contributed in gh-124153.)Add
PyUnicode_Equal()
function to the limited C API: test if two strings are equal. (Contributed by Victor Stinner in gh-124502.)Add
PyType_Freeze()
function to make a type immutable. (Contributed by Victor Stinner in gh-121654.)Add
PyUnstable_Object_EnableDeferredRefcount()
for enabling deferred reference counting, as outlined in PEP 703.Add
PyMonitoring_FireBranchLeftEvent()
andPyMonitoring_FireBranchRightEvent()
for generatingBRANCH_LEFT
andBRANCH_RIGHT
events, respectively.Add
Py_fopen()
function to open a file. Similar to thefopen()
function, but the path parameter is a Python object and an exception is set on error. Add alsoPy_fclose()
function to close a file. (Contributed by Victor Stinner in gh-127350.)Add support of nullable arguments in
PyArg_ParseTuple()
and similar functions. Adding?
after any format unit makesNone
be accepted as a value. (Contributed by Serhiy Storchaka in gh-112068.)The
k
andK
formats inPyArg_ParseTuple()
and similar functions now use__index__()
if available, like all other integer formats. (Contributed by Serhiy Storchaka in gh-112068.)Add macros
Py_PACK_VERSION()
andPy_PACK_FULL_VERSION()
for bit-packing Python version numbers. (Contributed by Petr Viktorin in gh-128629.)Add
PyUnstable_IsImmortal()
for determining whether an object is immortal, for debugging purposes.Add
PyImport_ImportModuleAttr()
andPyImport_ImportModuleAttrString()
helper functions to import a module and get an attribute of the module. (Contributed by Victor Stinner in gh-128911.)Add support for a new
p
format unit inPy_BuildValue()
that allows to take a C integer and produce a Pythonbool
object. (Contributed by Pablo Galindo in bpo-45325.)Add
PyUnstable_Object_IsUniqueReferencedTemporary()
to determine if an object is a unique temporary object on the interpreter’s operand stack. This can be used in some cases as a replacement for checking ifPy_REFCNT()
is1
for Python objects passed as arguments to C API functions.Add
PyUnstable_Object_IsUniquelyReferenced()
as a replacement forPy_REFCNT(op) == 1
on free threaded builds. (Contributed by Peter Bierma in gh-133140.)
Limited C API changes¶
In the limited C API 3.14 and newer,
Py_TYPE()
andPy_REFCNT()
are now implemented as an opaque function call to hide implementation details. (Contributed by Victor Stinner in gh-120600 and gh-124127.)Remove the
PySequence_Fast_GET_SIZE
,PySequence_Fast_GET_ITEM
andPySequence_Fast_ITEMS
macros from the limited C API, since these macros never worked in the limited C API. KeepPySequence_Fast()
in the limited C API. (Contributed by Victor Stinner in gh-91417.)
Porting to Python 3.14¶
Py_Finalize()
now deletes all interned strings. This is backwards incompatible to any C-Extension that holds onto an interned string after a call toPy_Finalize()
and is then reused after a call toPy_Initialize()
. Any issues arising from this behavior will normally result in crashes during the execution of the subsequent call toPy_Initialize()
from accessing uninitialized memory. To fix, use an address sanitizer to identify any use-after-free coming from an interned string and deallocate it during module shutdown. (Contributed by Eddie Elizondo in gh-113601.)The Unicode Exception Objects C API now raises a
TypeError
if its exception argument is not aUnicodeError
object. (Contributed by Bénédikt Tran in gh-127691.)
The interpreter internally avoids some reference count modifications when loading objects onto the operands stack by borrowing references when possible. This can lead to smaller reference count values compared to previous Python versions. C API extensions that checked
Py_REFCNT()
of1
to determine if an function argument is not referenced by any other code should instead usePyUnstable_Object_IsUniqueReferencedTemporary()
as a safer replacement.Private functions promoted to public C APIs:
_PyBytes_Join()
:PyBytes_Join()
_PyLong_IsNegative()
:PyLong_IsNegative()
_PyLong_IsPositive()
:PyLong_IsPositive()
_PyLong_IsZero()
:PyLong_IsZero()
_PyLong_Sign()
:PyLong_GetSign()
_PyUnicodeWriter_Dealloc()
:PyUnicodeWriter_Discard()
_PyUnicodeWriter_Finish()
:PyUnicodeWriter_Finish()
_PyUnicodeWriter_Init()
: usePyUnicodeWriter_Create()
_PyUnicodeWriter_Prepare()
: (no replacement)_PyUnicodeWriter_PrepareKind()
: (no replacement)_PyUnicodeWriter_WriteChar()
:PyUnicodeWriter_WriteChar()
_PyUnicodeWriter_WriteStr()
:PyUnicodeWriter_WriteStr()
_PyUnicodeWriter_WriteSubstring()
:PyUnicodeWriter_WriteSubstring()
_PyUnicode_EQ()
:PyUnicode_Equal()
_PyUnicode_Equal()
:PyUnicode_Equal()
_Py_GetConfig()
:PyConfig_Get()
andPyConfig_GetInt()
_Py_HashBytes()
:Py_HashBuffer()
_Py_fopen_obj()
:Py_fopen()
The pythoncapi-compat project can be used to get most of these new functions on Python 3.13 and older.
Descontinuados¶
The
Py_HUGE_VAL
macro is soft deprecated, usePy_INFINITY
instead. (Contributed by Sergey B Kirpichev in gh-120026.)Macros
Py_IS_NAN
,Py_IS_INFINITY
andPy_IS_FINITE
are soft deprecated, use insteadisnan
,isinf
andisfinite
available frommath.h
since C99. (Contributed by Sergey B Kirpichev in gh-119613.)Non-tuple sequences are deprecated as argument for the
(items)
format unit inPyArg_ParseTuple()
and other argument parsing functions if items contains format units which store a borrowed buffer or a borrowed reference. (Contributed by Serhiy Storchaka in gh-50333.)The previously undocumented function
PySequence_In()
is soft deprecated. UsePySequence_Contains()
instead. (Contributed by Yuki Kobayashi in gh-127896.)
The
PyMonitoring_FireBranchEvent
function is deprecated and should be replaced with calls toPyMonitoring_FireBranchLeftEvent()
andPyMonitoring_FireBranchRightEvent()
.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()
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()
: replace_PyUnicodeWriter_WriteASCIIString(&writer, str)
withPyUnicodeWriter_WriteASCII(writer, str)
._PyUnicodeWriter_WriteLatin1String()
: substitua_PyUnicodeWriter_WriteLatin1String(&writer, str)
porPyUnicodeWriter_WriteUTF8(writer, str)
._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.)
Remoção pendente no Python 3.15¶
A cópia empacotada do
libmpdecimal
.The
PyImport_ImportModuleNoBlock()
: usePyImport_ImportModule()
.PyWeakref_GetObject()
ePyWeakref_GET_OBJECT()
: UsePyWeakref_GetRef()
. O projeto pythoncapi-compat pode ser usado para usarPyWeakref_GetRef()
no Python 3.12 e versões anteriores.O tipo
Py_UNICODE
e a macroPy_UNICODE_WIDE
: usewchar_t
.PyUnicode_AsDecodedObject()
: usePyCodec_Decode()
.PyUnicode_AsDecodedUnicode()
: UsePyCodec_Decode()
; Note que alguns codecs (por exemplo, “base64”) podem retornar um tipo diferente destr
, tal comobytes
.PyUnicode_AsEncodedObject()
: usePyCodec_Encode()
.PyUnicode_AsEncodedUnicode()
: UsePyCodec_Encode()
; Note que alguns codecs (por exemplo, “base64”) podem retornar um tipo diferente debytes
, tal comstr
.Funções de inicialização do Python, descontinuadas no Python 3.9:
Py_GetPath()
: UsePyConfig_Get("module_search_paths")
(sys.path
).Py_GetPrefix()
: UsePyConfig_Get("base_prefix")
(sys.base_prefix
). UsePyConfig_Get("prefix")
(sys.prefix
) se ambientes virtuais precisam ser tratados.Py_GetExecPrefix()
: UsePyConfig_Get("base_exec_prefix")
(sys.base_exec_prefix
). UsePyConfig_Get("exec_prefix")
(sys.exec_prefix
) se ambientes virtuais precisam ser tratados.Py_GetProgramFullPath()
: UsePyConfig_Get("executable")
(sys.executable
).Py_GetProgramName()
: UsePyConfig_Get("executable")
(sys.executable
).Py_GetPythonHome()
: UsePyConfig_Get("home")
ou a variável de ambientePYTHONHOME
.
O projeto pythoncapi-compat pode ser usado para obter
PyConfig_Get()
no Python 3.13 e versões anteriores.Funções para configurar a inicialização do Python, descontinuadas no Python 3.11:
PySys_SetArgvEx()
: definaPyConfig.argv
.PySys_SetArgv()
: definaPyConfig.argv
.Py_SetProgramName()
: definaPyConfig.program_name
.Py_SetPythonHome()
: definaPyConfig.home
.PySys_ResetWarnOptions()
: apaguesys.warnoptions
ewarnings.filters
.
Em vez disso, a API
Py_InitializeFromConfig()
deve ser usada comPyConfig
.Variáveis de configuração globais
Py_DebugFlag
: UsePyConfig.parser_debug
ouPyConfig_Get("parser_debug")
.Py_VerboseFlag
: UsePyConfig.verbose
ouPyConfig_Get("verbose")
.Py_InteractiveFlag
: UsePyConfig.interactive
ouPyConfig_Get("interactive")
.Py_InspectFlag
: UsePyConfig.inspect
ouPyConfig_Get("inspect")
.Py_OptimizeFlag
: UsePyConfig.optimization_level
ouPyConfig_Get("optimization_level")
.Py_NoSiteFlag
: UsePyConfig.site_import
ouPyConfig_Get("site_import")
.Py_BytesWarningFlag
: UsePyConfig.bytes_warning
ouPyConfig_Get("bytes_warning")
.Py_FrozenFlag
: UsePyConfig.pathconfig_warnings
ouPyConfig_Get("pathconfig_warnings")
.Py_IgnoreEnvironmentFlag
: UsePyConfig.use_environment
ouPyConfig_Get("use_environment")
.Py_DontWriteBytecodeFlag
: UsePyConfig.write_bytecode
ouPyConfig_Get("write_bytecode")
.Py_NoUserSiteDirectory
: UsePyConfig.user_site_directory
ouPyConfig_Get("user_site_directory")
.Py_UnbufferedStdioFlag
: UsePyConfig.buffered_stdio
ouPyConfig_Get("buffered_stdio")
.Py_HashRandomizationFlag
: UsePyConfig.use_hash_seed
ePyConfig.hash_seed
ouPyConfig_Get("hash_seed")
.Py_IsolatedFlag
: UsePyConfig.isolated
ouPyConfig_Get("isolated")
.Py_LegacyWindowsFSEncodingFlag
: UsePyPreConfig.legacy_windows_fs_encoding
ouPyConfig_Get("legacy_windows_fs_encoding")
.Py_LegacyWindowsStdioFlag
: UsePyConfig.legacy_windows_stdio
ouPyConfig_Get("legacy_windows_stdio")
.Py_FileSystemDefaultEncoding
,Py_HasFileSystemDefaultEncoding
: UsePyConfig.filesystem_encoding
ouPyConfig_Get("filesystem_encoding")
.Py_FileSystemDefaultEncodeErrors
: UsePyConfig.filesystem_errors
ouPyConfig_Get("filesystem_errors")
.Py_UTF8Mode
: UsePyPreConfig.utf8_mode
ouPyConfig_Get("utf8_mode")
. (vejaPy_PreInitialize()
)
A API
Py_InitializeFromConfig()
deve ser usada comPyConfig
para definir essas opções. OuPyConfig_Get()
pode ser usado para obter essas opções em tempo de execução.
Remoção pendente no Python 3.18¶
Funções privadas descontinuadas (gh-128863):
_PyBytes_Join()
: usePyBytes_Join()
._PyDict_GetItemStringWithError()
: usePyDict_GetItemStringRef()
._PyDict_Pop()
:PyDict_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_WriteUTF8(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()
.
O projeto pythoncapi-compat pode ser usado para obter essas novas funções públicas no Python 3.13 e versões anteriores.
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.
Removidos¶
Creating
immutable types
with mutable bases was deprecated since 3.12 and now raises aTypeError
.Remove
PyDictObject.ma_version_tag
member which was deprecated since Python 3.12. Use thePyDict_AddWatcher()
API instead. (Contributed by Sam Gross in gh-124296.)Remove the private
_Py_InitializeMain()
function. It was a provisional API added to Python 3.8 by PEP 587. (Contributed by Victor Stinner in gh-129033.)The undocumented APIs
Py_C_RECURSION_LIMIT
andPyThreadState.c_recursion_remaining
, added in 3.13, are removed without a deprecation period. Please usePy_EnterRecursiveCall()
to guard against runaway recursion in C code. (Removed in gh-133079, see also gh-130396.)