O que há de novo no Python 3.7¶
- Editor:
Elvis Pranskevichus <elvis@magic.io>
Este artigo explica os novos recursos no Python 3.7, em comparação com 3.6. Python 3.7 foi lançado em 27 de Junho de 2018. Veja changelog para uma lista completa de mudanças.
Resumo – Destaques da versão¶
Novos recursos de sintaxe:
PEP 563, avaliação postergada de anotações de tipos.
Alterações de sintaxe incompatíveis com versões anteriores:
Novos módulos de biblioteca:
Novos recursos embutidos:
PEP 553, a nova função
breakpoint()
.;
Melhorias no modelo de dados Python:
PEP 562, personalização de acesso aos atributos do módulo.
PEP 560, suporte principal para o módulo typing e tipos genéricos.
a natureza de preservação da ordem de inserção de objetos dict foi declarada como uma parte oficial da especificação da linguagem Python.
Melhorias significativas na biblioteca padrão:
O módulo
asyncio
recebeu novos recursos, significativo à melhorias de usabilidade e desempenho.O módulo
time
ganhou suporte para funções com resolução de nanossegundos.
Melhorias na implementação do CPython:
Evitando o uso de ASCII como a codificação de texto padrão:
PEP 552, .pycs determinísticos
PEP 565, aprimorada o tratamento de
DeprecationWarning
Melhorias na API C:
PEP 539, nova API C para armazenamento local de thread
Melhorias na documentação:
PEP 545, Traduções da documentação do Python
Novas traduções da documentação: japonês, francês e coreano.
Esta versão apresenta melhorias de desempenho notáveis em muitas áreas. A seção Otimizações os lista em detalhes.
Para uma lista de mudanças que podem afetar a compatibilidade com versões anteriores do Python, consulte a seção Porting to Python 3.7.
Novas funcionalidades¶
PEP 563: Avaliação Postergada de Anotações¶
O advento das dicas de tipo no Python revelou dois problemas de usabilidade gritantes com a funcionalidade das anotações adicionadas em PEP 3107 e refinadas ainda mais em PEP 526:
as anotações só podiam usar nomes que já estavam disponíveis no escopo atual, ou seja, não suportavam referências de encaminhamento de nenhum tipo; e
anotar o código-fonte teve efeitos adversos no tempo de inicialização dos programas Python.
Ambos os problemas são corrigidos com o adiamento da avaliação das anotações. Em vez de compilar o código que executa expressões em anotações em seu tempo de definição, o compilador armazena a anotação em um formato de string equivalente ao AST da expressão em questão. Se necessário, as anotações podem ser resolvidas em tempo de execução usando digitando.get_type_hints()
. No caso comum em que isso não é necessário, as anotações são mais baratas de armazenar (uma vez que strings curtas são internadas pelo interpretador) e tornam o tempo de inicialização mais rápido.
Em termos de usabilidade, as anotações agora suportam referências futuras, tornando a seguinte sintaxe válida:
class C:
@classmethod
def from_string(cls, source: str) -> C:
...
def validate_b(self, obj: B) -> bool:
...
class B:
...
Como essa mudança quebra a compatibilidade, o novo comportamento precisa ser habilitado por módulo no Python 3.7 usando uma importação de __future__
from __future__ import annotations
Ele se tornará o padrão no Python 3.10.
Ver também
- PEP 563 – avaliação postergada de anotações de tipos
PEP escrita e implementada por Łukasz Langa.
PEP 538: Coerção de localidade C legada¶
Um desafio contínuo dentro da série Python 3 tem sido determinar uma estratégia padrão sensata para lidar com a suposição de codificação de texto “ASCII de 7 bits” atualmente implícita pelo uso da localidade C ou POSIX padrão em plataformas não Windows.
A PEP 538 atualiza a interface de linha de comando do interpretador padrão para forçar automaticamente essa localidade para uma localidade baseada em UTF-8 disponível conforme descrito na documentação da nova variável de ambiente PYTHONCOERCECLOCALE
. Configurar automaticamente LC_CTYPE
desta forma significa que tanto o interpretador central quanto as extensões C com reconhecimento da localidade (como readline
) irão presumir o uso de UTF-8 como a codificação de texto padrão, ao invés de ASCII.
A definição de suporte de plataforma na PEP 11 também foi atualizada para limitar o suporte de manipulação de texto completo para localidades não baseadas em ASCII adequadamente configuradas.
Como parte dessa mudança, o tratador de erros padrão para stdin
e stdout
agora é surrogateescape
(em vez de strict
) ao usar qualquer uma das localidades de destino de coerção definidas (atualmente C.UTF-8
, C.utf8
e UTF-8
). O tratador de erros padrão para stderr
continua a ser backslashreplace
, independente da localidade.
A coerção de localidade é silenciosa por padrão, mas para ajudar na depuração de problemas de integração potencialmente relacionados à localidade, avisos explícitos (emitidos diretamente em stderr
) podem ser solicitados configurando PYTHONCOERCECLOCALE=warn
. Essa configuração também fará com que o tempo de execução do Python emita um aviso se a localidade C legada permanecer ativa quando o interpretador principal for inicializado.
Embora a coerção de localidade PEP 538 tenha o benefício de também afetar os módulos de extensão (como GNU readline
), bem como processos filhos (incluindo aqueles que executam aplicativos não Python e versões mais antigas do Python), tem a desvantagem de exigir que uma localidade de destino adequado esteja presente no sistema em execução. Para tratador melhor o caso em que nenhuma localidade de destino adequado está disponível (como ocorre no RHEL/CentOS 7, por exemplo), o Python 3.7 também implementa PEP 540: Modo de tempo de execução UTF-8 forçado.
Ver também
- PEP 538 – Forçando a localidade C legada para uma localidade baseada em UTF-8
PEP escrita e implementada por Nick Coghlan.
PEP 540: Modo de tempo de execução UTF-8 forçado¶
A nova opção de linha de comando -X
utf8
e a variável de ambiente PYTHONUTF8
podem ser usadas para habilitar o modo UTF-8 do Python.
Quando no modo UTF-8, o CPython ignora as configurações de localidade e usa a codificação UTF-8 por padrão. Os tratador de erros para fluxos sys.stdin
e sys.stdout
são configurados para surrogateescape
.
O modo UTF-8 forçado pode ser usado para alterar o comportamento de manipulação de texto em um interpretador Python embutido sem alterar as configurações de localidade de uma aplicação embutida.
Embora o modo UTF-8 da PEP 540 tenha a vantagem de funcionar independentemente de quais localidades estão disponíveis no sistema em execução, ele tem a desvantagem de não ter efeito sobre os módulos de extensão (como GNU readline
) , processos filho executando aplicativos não-Python e processos filho executando versões anteriores do Python. Para reduzir o risco de corromper dados de texto ao se comunicar com tais componentes, o Python 3.7 também implementa PEP 540: Modo de tempo de execução UTF-8 forçado).
O modo UTF-8 é habilitado por padrão quando a localidade é C
ou POSIX
, e o recurso de coerção de localidade PEP 538 falha em mudá-la para uma alternativa baseada em UTF-8 (seja falha é devido a PYTHONCOERCECLOCALE=0
sendo definido, LC_ALL
sendo definido, ou a falta de uma localidade de destino adequada).
Ver também
- PEP 540 – Adiciona um novo modo UTF-8
PEP escrito e implementado por Victor Stinner
PEP 553: breakpoint()
embutida¶
Python 3.7 inclui a nova função embutida breakpoint()
como uma maneira fácil e consistente de entrar no depurador Python.
breakpoint()
embutida chama sys.breakpointhook()
. Por padrão, o último importa pdb
e então chama pdb.set_trace()
, mas ao ligar sys.breakpointhook()
à função de sua escolha, breakpoint()
pode entrar em qualquer depurador. Além disso, a variável de ambiente PYTHONBREAKPOINT
pode ser configurada para o chamável de seu depurador de escolha. Defina PYTHONBREAKPOINT=0
para desabilitar completamente o breakpoint()
embutida.
Ver também
- PEP 553 – breakpoint() embutida
PEP escrita e implementada por Barry Warsaw
PEP 539: Nova API C para armazenamento local de thread¶
Enquanto Python fornece uma API C para suporte de armazenamento local de thread; a existente API da armazenamento local de thread (TLS) usou int para representar as chaves TLS em todas as plataformas. Isso geralmente não tem sido um problema para plataformas oficialmente suportadas, mas isso não é compatível com POSIX, nem portátil em qualquer sentido prático.
A PEP 539 muda isso fornecendo uma nova API de armazenamento específico de thread (TSS) para CPython que substitui o uso da API de TLS existente dentro do interpretador CPython, enquanto descontinua a API existente. A API de TSS usa um novo tipo Py_tss_t
em vez de int para representar as chaves de TSS – um tipo não visível cuja definição pode depender da implementação TLS subjacente. Portanto, isso permitirá construir CPython em plataformas onde a chave nativa de TLS é definida de uma forma que não pode ser convertida com segurança para int.
Observe que em plataformas onde a chave TLS nativa é definida de uma forma que não pode ser convertida com segurança para int, todas as funções da API TLS existente serão no-op e retornarão falha imediatamente. Isso indica claramente que a API antiga não é suportada em plataformas onde não pode ser usada de forma confiável e que nenhum esforço será feito para adicionar tal suporte.
Ver também
- PEP 539 – Uma nova API C para armazenamento local de thread no CPython
PEP escrita por Erik M. Bray; implementação por Masayuki Yamamoto.
PEP 562: Personalização de acesso aos atributos do módulo¶
Python 3.7 permite definir __getattr__()
em módulos e irá chamá-lo sempre que um atributo de módulo não for encontrado. Definir __dir__()
em módulos agora também é permitido.
Um exemplo típico de onde isso pode ser útil é a descontinuação do atributo do módulo e o carregamento preguiçoso ou lazy.
Ver também
- PEP 562 – Módulo
__getattr__
e__dir__
PEP escrita e implementada por Ivan Levkivskyi
PEP 564: Novas funções de tempo com resolução de nanossegundos¶
A resolução dos relógios em sistemas modernos pode exceder a precisão limitada de um número de ponto flutuante retornado pela função time.time()
e suas variantes. Para evitar perda de precisão, PEP 564 adiciona seis novas variantes em “nanossegundos” das funções de temporizador existentes ao módulo time
:
As novas funções retornam o número de nanossegundos como um valor inteiro.
Medições mostram que no Linux e no Windows a resolução de time.time_ns()
é aproximadamente 3 vezes melhor do que time.time()
.
Ver também
- PEP 564 – Adiciona novas funções de tempo com resolução de nanossegundos
PEP escrito e implementado por Victor Stinner
PEP 565: Mostra DeprecationWarning em __main__
¶
O tratamento padrão de DeprecationWarning
foi alterado de forma que esses avisos sejam mais uma vez mostrados por padrão, mas apenas quando o código que os aciona está sendo executado diretamente no módulo __main__
. Como resultado, os desenvolvedores de scripts de arquivo único e aqueles que usam Python interativamente devem mais uma vez começar a ver avisos de descontinuação para as APIs que usam, mas os avisos de descontinuação acionados por aplicações importadas, biblioteca e módulos de estrutura continuarão ocultos por padrão.
Como resultado dessa mudança, a biblioteca padrão agora permite que os desenvolvedores escolham entre três comportamentos diferentes de aviso de descontinuação:
FutureWarning
: sempre exibida por padrão, recomendado para avisos que devem ser vistos pelos usuários finais da aplicação (por exemplo, para definições de configuração de aplicações descontinuadas).DeprecationWarning
: exibida por padrão apenas em__main__
e ao executar testes, recomendado para avisos que devem ser vistos por outros desenvolvedores Python onde uma atualização de versão pode resultar em mudança de comportamento ou um erro.PendingDeprecationWarning
: exibida por padrão apenas ao executar testes, destinados a casos em que uma atualização de versão futura mudará a categoria de aviso paraDeprecationWarning
ouFutureWarning
.
Anteriormente, ambas DeprecationWarning
e PendingDeprecationWarning
eram visíveis apenas durante a execução de testes, o que significava que os desenvolvedores principalmente escrevendo scripts de arquivo único ou usando Python interativamente poderiam ser surpreendidos por alterações nas APIs que usavam.
Ver também
- PEP 565 – Show DeprecationWarning in
__main__
PEP escrita e implementada por Nick Coghlan
PEP 560: Suporte básico para módulo typing
e tipos genéricos¶
Inicialmente a PEP 484 foi projetado de tal forma que não introduziria nenhuma mudança no interpretador CPython central. Agora que type hints e o módulo typing
são amplamente usados pela comunidade, então esta restrição foi removida. A PEP introduz dois métodos especiais __class_getitem__()
e __mro_entries__
, esses métodos agora são usados pela maioria das classes e construções especiais em typing
. Como resultado, a velocidade de várias operações com tipos aumentou em até 7 vezes, os tipos genéricos podem ser usados sem conflitos de metaclasse e vários bugs de longa data no módulo typing
foram corrigidos.
Ver também
- PEP 560 – Suporte básico para módulo typing e tipos genéricos
PEP escrita e implementada por Ivan Levkivskyi
PEP 552: Arquivos .pyc baseados em hash¶
O Python tradicionalmente verifica a atualização dos arquivos de cache em bytecode (ou seja, arquivos .pyc
) comparando os metadados da fonte (registro de data e hora e tamanho da última modificação) com os metadados da fonte salvos no cabeçalho do arquivo de cache quando foi gerado. Embora eficaz, esse método de invalidação tem suas desvantagens. Quando os registros de data e hora do sistema de arquivos são muito grosseiros, o Python pode perder as atualizações de origem, levando à confusão do usuário. Além disso, ter um registro de data e hora no arquivo de cache é problemático para reprodutibilidade de compilação e sistemas de compilação baseados em conteúdo.
PEP 552 estende o formato pyc para permitir que o hash do arquivo de origem seja usado para invalidação em vez do registro de data e hora da fonte. Esses arquivos .pyc
são chamados de “baseados em hash”. Por padrão, Python ainda usa invalidação baseada em registro de data e hora e não gera arquivos .pyc
baseados em hash em tempo de execução. Arquivos .pyc
baseados em hash podem ser gerados com py_compile
ou compileall
.
Arquivos .pyc
baseados em hash vêm em duas variantes: verificados e não verificados. Python valida arquivos .pyc
baseados em hash verificados em relação aos arquivos fonte correspondentes em tempo de execução, mas não o faz para pycs baseados em hash não verificados. Arquivos .pyc
baseados em hash não verificados são uma otimização de desempenho útil para ambientes onde um sistema externo ao Python (por exemplo, o sistema de construção) é responsável por manter os arquivos .pyc
atualizados.
Veja a função Invalidação de bytecode em cache para mais informações.
Ver também
- PEP 552 – pycs determinísticos
PEP escrita e implementada por Benjamin Peterson
PEP 545: Traduções da documentação do Python¶
PEP 545 descreve o processo de criação a manutenção das traduções da documentação do Python.
Três novas traduções foram adicionadas:
Japonês: https://docs.python.org/ja/
Francês: https://docs.python.org/fr/
Coreano: https://docs.python.org/ko/
Ver também
- PEP 545 – Traduções da documentação do Python
PEP escrita e implementada por Julien Palard, Inada Naoki e Victor Stinner.
Modo de Desenvolvimento do Python (-X dev)¶
A nova opção de linha de comando -X
dev
ou a nova variável de ambiente PYTHONDEVMODE
pode ser usada para habilitar Modo de Desenvolvimento do Python. Quando está no modo de desenvolvimento, o Python executa verificações adicionais em tempo de execução que são muito caras para serem habilitadas por padrão. Veja a documentação Modo de Desenvolvimento do Python para a descrição completa.
Outras mudanças na linguagem¶
Uma expressão
await
e compreensões contendo uma cláusulaasync for
eram ilegais nas expressões em literais de strings formatadas devido a um problema com a implementação. No Python 3.7, esta restrição foi retirada.Mais de 255 argumentos agora podem ser passados para uma função, e uma função agora pode ter mais de 255 parâmetros. (Contribuição de Serhiy Storchaka em bpo-12844 e bpo-18896.)
bytes.fromhex()
ebytearray.fromhex()
agora ignoram todos os espaços em branco ASCII, não apenas espaços. (Contribuição de Robert Xiao em bpo-28927.)str
,bytes
ebytearray
ganharam suporte para o novo métodoisascii()
, que pode ser usado para testar se uma string ou bytes contêm apenas os caracteres ASCII. (Contribuição de INADA Naoki em bpo-32677.)ImportError
agora exibe o nome do módulo e o caminho do módulo__file__
quandofrom ... import ...
falha. (Contribuição de Matthias Bussonnier em bpo-29546.)Importações circulares envolvendo importações absolutas com ligação de um submódulo a um nome agora são suportadas. (Contribuição de Serhiy Storchaka em bpo-30024.)
object.__format__(x, '')
agora é equivalente astr(x)
em vez deformat(str(self), '')
. (Contribuição de Serhiy Storchaka em bpo-28974.)Para melhor prover suporte à criação dinâmica de rastreamentos de pilha,
types.TracebackType
agora pode ser instanciado a partir do código Python, e o atributotb_next
em tracebacks agora é gravável. (Contribuição de Nathaniel J. Smith em bpo-30579.)Ao usar a opção
-m
,sys.path[0]
agora é expandido para o caminho completo do diretório inicial, em vez de ser deixado como o diretório vazio (o que permite importações do atual diretório de trabalho no momento em que ocorre uma importação) (Contribuição de Nick Coghlan em bpo-33053.)A nova opção
-X
importtime
ou a variável de ambientePYTHONPROFILEIMPORTTIME
pode ser usada para mostrar o tempo de cada importação de módulo. (Contribuição de Inada Naoki em bpo-31415.)
Novos módulos¶
contextvars¶
O novo módulo contextvars
e um conjunto de novas APIs C introduzem suporte para variáveis de contexto. Variáveis de contexto são conceitualmente semelhantes às variáveis locais de thread. Ao contrário do TLS, as variáveis de contexto oferecem suporte a código assíncrono corretamente.
Os módulos asyncio
e decimal
foram atualizados para usar e prover suporte a variáveis de contexto prontas para uso. Particularmente o contexto decimal ativo agora é armazenado em uma variável de contexto, o que permite que operações decimais funcionem com o contexto correto em código assíncrono.
Ver também
- PEP 567 – Variáveis de contexto
PEP escrita e implementada por Yury Selivanov
dataclasses¶
O novo decorador dataclass()
fornece uma maneira de declarar classes de dados. Uma classe de dados descreve seus atributos usando anotações de variáveis de classe. Seu construtor e outros métodos mágicos, como __repr__()
, __eq__()
e __hash__()
são gerados automaticamente.
Exemplo:
@dataclass
class Point:
x: float
y: float
z: float = 0.0
p = Point(1.5, 2.5)
print(p) # produces "Point(x=1.5, y=2.5, z=0.0)"
Ver também
- PEP 557 – Classes de dados
PEP escrita e implementada por Eric V. Smith
importlib.resources¶
O novo módulo importlib.resources
fornece diversas novas APIs e um novo ABC para acesso, abertura e leitura de recursos dentro de pacotes. Os recursos são aproximadamente semelhantes aos arquivos dentro dos pacotes, mas não precisam ser arquivos reais no sistema de arquivos físico. Os carregadores de módulo podem fornecer uma função get_resource_reader()
que retorna uma instância importlib.abc.ResourceReader
para suportar esta nova API. Carregadores embutidos de caminho de arquivo e carregadores de arquivo zip oferecem suporte a isso.
(Contribuição de Barry Warsaw e Brett Cannon em bpo-32248.)
Ver também
importlib_resources – um backport do PyPI para versões anteriores do Python.
Módulos melhorados¶
argparse¶
O novo método ArgumentParser.parse_intermixed_args()
permite misturar opções e argumentos posicionais. (Contribuição de paul.j3 em bpo-14191.)
asyncio¶
O módulo asyncio
recebeu muitos novos recursos, usabilidade e melhorias de desempenho. Mudanças notáveis incluem:
A nova função provisória
asyncio.run()
pode ser usada para executar uma corrotina a partir de código síncrono criando e destruindo automaticamente o laço de eventos. (Contribuição de Yury Selivanov em bpo-32314.)asyncio ganhou suporte para
contextvars
.loop.call_soon()
,loop.call_soon_threadsafe()
,loop.call_later()
,loop.call_at()
eFuture.add_done_callback()
têm um novo parâmetro somente-nomeado opcional context.Tasks
agora rastreia seu contexto automaticamente. Veja PEP 567 para mais detalhes. (Contribuição de Yury Selivanov em bpo-32436.)A nova função
asyncio.create_task()
foi adicionada como um atalho paraasyncio.get_event_loop().create_task()
. (Contribuição de Andrew Svetlov em bpo-32311.)O novo método
loop.start_tls()
pode ser usado para atualizar uma conexão existente para TLS. (Contribuição de Yury Selivanov em bpo-23749.)O novo método
loop.sock_recv_into()
permite a leitura de dados de um soquete diretamente em um buffer fornecido, tornando possível reduzir as cópias de dados. (Contribuição de Antoine Pitrou em bpo-31819.)A nova função
asyncio.current_task()
retorna a instânciaTask
atualmente em execução, e a nova funçãoasyncio.all_tasks()
retorna um conjunto de todas as instânciasTask
existentes em um determinado laço. Os métodosTask.current_task()
eTask.all_tasks()
foram descontinuados. (Contribuição de Andrew Svetlov em bpo-32250.)A nova classe provisória
BufferedProtocol
permite implementar protocolos de streaming com controle manual sobre o buffer de recebimento. (Contribuição de Yury Selivanov em bpo-32251.)A nova função
asyncio.get_running_loop()
retorna o laço atualmente em execução e levanta uma exceçãoRuntimeError
se nenhum laço estiver em execução. Isto contrasta comasyncio.get_event_loop()
, que irá criar um novo laço de eventos se nenhum estiver em execução. (Contribuição de Yury Selivanov em bpo-32269.)O novo método de corrotina
StreamWriter.wait_closed()
permite esperar até que o gravador de fluxo seja fechado. O novo métodoStreamWriter.is_closing()
pode ser usado para determinar se o gravador está fechando. (Contribuição de Andrew Svetlov em bpo-32391.)O novo método de corrotina
loop.sock_sendfile()
permite enviar arquivos usandoos.sendfile
quando possível. (Contribuição de Andrew Svetlov em bpo-32410.)Os novos métodos
Future.get_loop()
eTask.get_loop()
retornam a instância do laço no qual uma tarefa ou um future foi criado.Server.get_loop()
permite fazer o mesmo para objetosasyncio.Server
. (Contribuição de Yury Selivanov em bpo-32415 e Srinivas Reddy Thatiparthy em bpo-32418.)Agora é possível controlar como as instâncias de
asyncio.Server
começam a servir. Anteriormente, o servidor começaria a servir imediatamente após ser criado. O novo argumento nomeado start_serving paraloop.create_server()
eloop.create_unix_server()
, bem comoServer.start_serving()
eServer.serve_forever()
podem ser usados para dissociar a instanciação e o serviço do servidor. O novo métodoServer.is_serving()
retornaTrue
se o servidor estiver servindo. Os objetosServer
agora são gerenciadores de contexto assíncronos:srv = await loop.create_server(...) async with srv: # algum código # Neste ponto, srv é fechado e não mais aceita novas conexões.
(Contribuição de Yury Selivanov em bpo-32662.)
Objetos de retorno de chamada retornados por
loop.call_later()
ganharam o novo métodowhen()
que retorna um registro de data e hora de retorno de chamada agendado absoluto. (Contribuição de Andrew Svetlov em bpo-32741.)O método
loop.create_datagram_endpoint()
ganhou suporte para soquetes Unix. (Contribuição de Quentin Dawans em bpo-31245.)As funções
asyncio.open_connection()
,asyncio.start_server()
, os métodosloop.create_connection()
,loop.create_server()
,loop.create_accepted_socket()
e suas variantes de soquete UNIX correspondentes agora aceitam o argumento nomeado ssl_handshake_timeout. (Contribuição de Neil Aspinall em bpo-29970.)O novo método
Handle.cancelled()
retornaTrue
se o retorno de chamada foi cancelado. (Contribuição de Marat Sharafutdinov em bpo-31943.)A fonte de asyncio foi convertida para usar a sintaxe
async
/await
. (Contribuição de Andrew Svetlov em bpo-32193.)O novo método
ReadTransport.is_reading()
pode ser usado para determinar o estado de leitura do transporte. Além disso, chamadas paraReadTransport.resume_reading()
eReadTransport.pause_reading()
agora são idempotentes. (Contribuição de Yury Selivanov em bpo-32356.)Loop methods which accept socket paths now support passing path-like objects. (Contributed by Yury Selivanov in bpo-32066.)
In
asyncio
TCP sockets on Linux are now created withTCP_NODELAY
flag set by default. (Contributed by Yury Selivanov and Victor Stinner in bpo-27456.)Exceptions occurring in cancelled tasks are no longer logged. (Contributed by Yury Selivanov in bpo-30508.)
New
WindowsSelectorEventLoopPolicy
andWindowsProactorEventLoopPolicy
classes. (Contributed by Yury Selivanov in bpo-33792.)
Several asyncio
APIs have been
deprecated.
binascii¶
The b2a_uu()
function now accepts an optional backtick
keyword argument. When it’s true, zeros are represented by '`'
instead of spaces. (Contributed by Xiang Zhang in bpo-30103.)
calendar¶
The HTMLCalendar
class has new class attributes which ease
the customization of CSS classes in the produced HTML calendar.
(Contributed by Oz Tiram in bpo-30095.)
collections¶
collections.namedtuple()
now supports default values.
(Contributed by Raymond Hettinger in bpo-32320.)
compileall¶
compileall.compile_dir()
learned the new invalidation_mode parameter,
which can be used to enable
hash-based .pyc invalidation. The invalidation
mode can also be specified on the command line using the new
--invalidation-mode
argument.
(Contributed by Benjamin Peterson in bpo-31650.)
concurrent.futures¶
ProcessPoolExecutor
and
ThreadPoolExecutor
now
support the new initializer and initargs constructor arguments.
(Contributed by Antoine Pitrou in bpo-21423.)
The ProcessPoolExecutor
can now take the multiprocessing context via the new mp_context argument.
(Contributed by Thomas Moreau in bpo-31540.)
contextlib¶
The new nullcontext()
is a simpler and faster no-op
context manager than ExitStack
.
(Contributed by Jesse-Bakker in bpo-10049.)
The new asynccontextmanager()
,
AbstractAsyncContextManager
, and
AsyncExitStack
have been added to
complement their synchronous counterparts. (Contributed
by Jelle Zijlstra in bpo-29679 and bpo-30241,
and by Alexander Mohr and Ilya Kulakov in bpo-29302.)
cProfile¶
The cProfile
command line now accepts -m module_name
as an
alternative to script path. (Contributed by Sanyam Khurana in bpo-21862.)
crypt¶
The crypt
module now supports the Blowfish hashing method.
(Contributed by Serhiy Storchaka in bpo-31664.)
The mksalt()
function now allows specifying the number of rounds
for hashing. (Contributed by Serhiy Storchaka in bpo-31702.)
datetime¶
The new datetime.fromisoformat()
method constructs a datetime
object from a string
in one of the formats output by
datetime.isoformat()
.
(Contributed by Paul Ganssle in bpo-15873.)
The tzinfo
class now supports sub-minute offsets.
(Contributed by Alexander Belopolsky in bpo-5288.)
dbm¶
dbm.dumb
now supports reading read-only files and no longer writes the
index file when it is not changed.
decimal¶
The decimal
module now uses context variables
to store the decimal context.
(Contributed by Yury Selivanov in bpo-32630.)
dis¶
The dis()
function is now able to
disassemble nested code objects (the code of comprehensions, generator
expressions and nested functions, and the code used for building nested
classes). The maximum depth of disassembly recursion is controlled by
the new depth parameter.
(Contributed by Serhiy Storchaka in bpo-11822.)
distutils¶
README.rst
is now included in the list of distutils standard READMEs and
therefore included in source distributions.
(Contributed by Ryan Gonzalez in bpo-11913.)
enum¶
The Enum
learned the new _ignore_
class property,
which allows listing the names of properties which should not become
enum members.
(Contributed by Ethan Furman in bpo-31801.)
In Python 3.8, attempting to check for non-Enum objects in Enum
classes will raise a TypeError
(e.g. 1 in Color
); similarly,
attempting to check for non-Flag objects in a Flag
member will
raise TypeError
(e.g. 1 in Perm.RW
); currently, both operations
return False
instead and are deprecated.
(Contributed by Ethan Furman in bpo-33217.)
functools¶
functools.singledispatch()
now supports registering implementations
using type annotations.
(Contributed by Łukasz Langa in bpo-32227.)
gc¶
The new gc.freeze()
function allows freezing all objects tracked
by the garbage collector and excluding them from future collections.
This can be used before a POSIX fork()
call to make the GC copy-on-write
friendly or to speed up collection. The new gc.unfreeze()
functions
reverses this operation. Additionally, gc.get_freeze_count()
can
be used to obtain the number of frozen objects.
(Contributed by Li Zekun in bpo-31558.)
hmac¶
The hmac
module now has an optimized one-shot digest()
function, which is up to three times faster than HMAC()
.
(Contributed by Christian Heimes in bpo-32433.)
http.client¶
HTTPConnection
and HTTPSConnection
now support the new blocksize argument for improved upload throughput.
(Contributed by Nir Soffer in bpo-31945.)
http.server¶
SimpleHTTPRequestHandler
now supports the HTTP
If-Modified-Since
header. The server returns the 304 response status if
the target file was not modified after the time specified in the header.
(Contributed by Pierre Quentel in bpo-29654.)
SimpleHTTPRequestHandler
accepts the new directory
argument, in addition to the new --directory
command line argument.
With this parameter, the server serves the specified directory, by default it
uses the current working directory.
(Contributed by Stéphane Wirtel and Julien Palard in bpo-28707.)
The new ThreadingHTTPServer
class
uses threads to handle requests using ThreadingMixin
.
It is used when http.server
is run with -m
.
(Contributed by Julien Palard in bpo-31639.)
idlelib e IDLE¶
Multiple fixes for autocompletion. (Contributed by Louie Lu in bpo-15786.)
Module Browser (on the File menu, formerly called Class Browser), now displays nested functions and classes in addition to top-level functions and classes. (Contributed by Guilherme Polo, Cheryl Sabella, and Terry Jan Reedy in bpo-1612262.)
The Settings dialog (Options, Configure IDLE) has been partly rewritten to improve both appearance and function. (Contributed by Cheryl Sabella and Terry Jan Reedy in multiple issues.)
The font sample now includes a selection of non-Latin characters so that users can better see the effect of selecting a particular font. (Contributed by Terry Jan Reedy in bpo-13802.) The sample can be edited to include other characters. (Contributed by Serhiy Storchaka in bpo-31860.)
The IDLE features formerly implemented as extensions have been reimplemented as normal features. Their settings have been moved from the Extensions tab to other dialog tabs. (Contributed by Charles Wohlganger and Terry Jan Reedy in bpo-27099.)
Editor code context option revised. Box displays all context lines up to maxlines. Clicking on a context line jumps the editor to that line. Context colors for custom themes is added to Highlights tab of Settings dialog. (Contributed by Cheryl Sabella and Terry Jan Reedy in bpo-33642, bpo-33768, and bpo-33679.)
On Windows, a new API call tells Windows that tk scales for DPI. On Windows 8.1+ or 10, with DPI compatibility properties of the Python binary unchanged, and a monitor resolution greater than 96 DPI, this should make text and lines sharper. It should otherwise have no effect. (Contributed by Terry Jan Reedy in bpo-33656.)
New in 3.7.1:
A saída em N linhas (50 por padrão) é compactada até um limite inferior. N pode ser alterado na seção PyShell da página General da caixa de diálogo Settings. Menos linhas, mas possivelmente extra longas, podem ser espremidas clicando com o botão direito do mouse na saída. A saída compactada pode ser expandida no local clicando duas vezes no botão ou na área de transferência ou em uma janela separada clicando com o botão direito do mouse. (Contribuição de Tal Einat em bpo-1529353.)
The changes above have been backported to 3.6 maintenance releases.
NEW in 3.7.4:
Add “Run Customized” to the Run menu to run a module with customized settings. Any command line arguments entered are added to sys.argv. They re-appear in the box for the next customized run. One can also suppress the normal Shell main module restart. (Contributed by Cheryl Sabella, Terry Jan Reedy, and others in bpo-5680 and bpo-37627.)
New in 3.7.5:
Add optional line numbers for IDLE editor windows. Windows open without line numbers unless set otherwise in the General tab of the configuration dialog. Line numbers for an existing window are shown and hidden in the Options menu. (Contributed by Tal Einat and Saimadhav Heblikar in bpo-17535.)
importlib¶
The importlib.abc.ResourceReader
ABC was introduced to
support the loading of resources from packages. See also
importlib.resources.
(Contributed by Barry Warsaw, Brett Cannon in bpo-32248.)
importlib.reload()
now raises ModuleNotFoundError
if the module
lacks a spec.
(Contributed by Garvit Khatri in bpo-29851.)
importlib.find_spec()
now raises ModuleNotFoundError
instead of
AttributeError
if the specified parent module is not a package (i.e.
lacks a __path__
attribute).
(Contributed by Milan Oberkirch in bpo-30436.)
The new importlib.source_hash()
can be used to compute the hash of
the passed source. A hash-based .pyc file
embeds the value returned by this function.
io¶
The new TextIOWrapper.reconfigure()
method can be used to reconfigure the text stream with the new settings.
(Contributed by Antoine Pitrou in bpo-30526 and
INADA Naoki in bpo-15216.)
ipaddress¶
The new subnet_of()
and supernet_of()
methods of
ipaddress.IPv6Network
and ipaddress.IPv4Network
can
be used for network containment tests.
(Contributed by Michel Albert and Cheryl Sabella in bpo-20825.)
itertools¶
itertools.islice()
now accepts
integer-like objects
as start, stop,
and slice arguments.
(Contributed by Will Roberts in bpo-30537.)
locale¶
The new monetary argument to locale.format_string()
can be used
to make the conversion use monetary thousands separators and
grouping strings. (Contributed by Garvit in bpo-10379.)
The locale.getpreferredencoding()
function now always returns 'UTF-8'
on Android or when in the forced UTF-8 mode.
logging¶
Logger
instances can now be pickled.
(Contributed by Vinay Sajip in bpo-30520.)
The new StreamHandler.setStream()
method can be used to replace the logger stream after handler creation.
(Contributed by Vinay Sajip in bpo-30522.)
It is now possible to specify keyword arguments to handler constructors in
configuration passed to logging.config.fileConfig()
.
(Contributed by Preston Landers in bpo-31080.)
math¶
The new math.remainder()
function implements the IEEE 754-style remainder
operation. (Contributed by Mark Dickinson in bpo-29962.)
mimetypes¶
The MIME type of .bmp has been changed from 'image/x-ms-bmp'
to
'image/bmp'
.
(Contributed by Nitish Chandra in bpo-22589.)
msilib¶
The new Database.Close()
method can be used
to close the MSI database.
(Contributed by Berker Peksag in bpo-20486.)
multiprocessing¶
The new Process.close()
method
explicitly closes the process object and releases all resources associated
with it. ValueError
is raised if the underlying process is still
running.
(Contributed by Antoine Pitrou in bpo-30596.)
The new Process.kill()
method can
be used to terminate the process using the SIGKILL
signal on Unix.
(Contributed by Vitor Pereira in bpo-30794.)
Non-daemonic threads created by Process
are now
joined on process exit.
(Contributed by Antoine Pitrou in bpo-18966.)
os¶
os.fwalk()
now accepts the path argument as bytes
.
(Contributed by Serhiy Storchaka in bpo-28682.)
os.scandir()
gained support for file descriptors.
(Contributed by Serhiy Storchaka in bpo-25996.)
The new register_at_fork()
function allows registering Python
callbacks to be executed at process fork.
(Contributed by Antoine Pitrou in bpo-16500.)
Added os.preadv()
(combine the functionality of os.readv()
and
os.pread()
) and os.pwritev()
functions (combine the functionality
of os.writev()
and os.pwrite()
). (Contributed by Pablo Galindo in
bpo-31368.)
The mode argument of os.makedirs()
no longer affects the file
permission bits of newly created intermediate-level directories.
(Contributed by Serhiy Storchaka in bpo-19930.)
os.dup2()
now returns the new file descriptor. Previously, None
was always returned.
(Contributed by Benjamin Peterson in bpo-32441.)
The structure returned by os.stat()
now contains the
st_fstype
attribute on Solaris and its derivatives.
(Contributed by Jesús Cea Avión in bpo-32659.)
pathlib¶
The new Path.is_mount()
method is now available
on POSIX systems and can be used to determine whether a path is a mount point.
(Contributed by Cooper Ry Lees in bpo-30897.)
pdb¶
pdb.set_trace()
now takes an optional header keyword-only
argument. If given, it is printed to the console just before debugging
begins. (Contributed by Barry Warsaw in bpo-31389.)
pdb
command line now accepts -m module_name
as an alternative to
script file. (Contributed by Mario Corchero in bpo-32206.)
py_compile¶
py_compile.compile()
– and by extension, compileall
– now
respects the SOURCE_DATE_EPOCH
environment variable by
unconditionally creating .pyc
files for hash-based validation.
This allows for guaranteeing
reproducible builds of .pyc
files when they are created eagerly. (Contributed by Bernhard M. Wiedemann
in bpo-29708.)
pydoc¶
The pydoc server can now bind to an arbitrary hostname specified by the
new -n
command-line argument.
(Contributed by Feanil Patel in bpo-31128.)
queue¶
The new SimpleQueue
class is an unbounded FIFO queue.
(Contributed by Antoine Pitrou in bpo-14976.)
re¶
The flags re.ASCII
, re.LOCALE
and re.UNICODE
can be set within the scope of a group.
(Contributed by Serhiy Storchaka in bpo-31690.)
re.split()
now supports splitting on a pattern like r'\b'
,
'^$'
or (?=-)
that matches an empty string.
(Contributed by Serhiy Storchaka in bpo-25054.)
Regular expressions compiled with the re.LOCALE
flag no longer
depend on the locale at compile time. Locale settings are applied only
when the compiled regular expression is used.
(Contributed by Serhiy Storchaka in bpo-30215.)
FutureWarning
is now emitted if a regular expression contains
character set constructs that will change semantically in the future,
such as nested sets and set operations.
(Contributed by Serhiy Storchaka in bpo-30349.)
Compiled regular expression and match objects can now be copied
using copy.copy()
and copy.deepcopy()
.
(Contributed by Serhiy Storchaka in bpo-10076.)
signal¶
The new warn_on_full_buffer argument to the signal.set_wakeup_fd()
function makes it possible to specify whether Python prints a warning on
stderr when the wakeup buffer overflows.
(Contributed by Nathaniel J. Smith in bpo-30050.)
socket¶
The new socket.getblocking()
method
returns True
if the socket is in blocking mode and False
otherwise.
(Contributed by Yury Selivanov in bpo-32373.)
The new socket.close()
function closes the passed socket file descriptor.
This function should be used instead of os.close()
for better
compatibility across platforms.
(Contributed by Christian Heimes in bpo-32454.)
The socket
module now exposes the socket.TCP_CONGESTION
(Linux 2.6.13), socket.TCP_USER_TIMEOUT
(Linux 2.6.37), and
socket.TCP_NOTSENT_LOWAT
(Linux 3.12) constants.
(Contributed by Omar Sandoval in bpo-26273 and
Nathaniel J. Smith in bpo-29728.)
Support for socket.AF_VSOCK
sockets has been added to allow
communication between virtual machines and their hosts.
(Contributed by Cathy Avery in bpo-27584.)
Sockets now auto-detect family, type and protocol from file descriptor by default. (Contributed by Christian Heimes in bpo-28134.)
socketserver¶
socketserver.ThreadingMixIn.server_close()
now waits until all non-daemon
threads complete. socketserver.ForkingMixIn.server_close()
now waits
until all child processes complete.
Add a new socketserver.ForkingMixIn.block_on_close
class attribute to
socketserver.ForkingMixIn
and socketserver.ThreadingMixIn
classes. Set the class attribute to False
to get the pre-3.7 behaviour.
sqlite3¶
sqlite3.Connection
now exposes the backup()
method when the underlying SQLite library is at version 3.6.11 or higher.
(Contributed by Lele Gaifax in bpo-27645.)
The database argument of sqlite3.connect()
now accepts any
path-like object, instead of just a string.
(Contributed by Anders Lorentsen in bpo-31843.)
ssl¶
The ssl
module now uses OpenSSL’s builtin API instead of
match_hostname()
to check a host name or an IP address. Values
are validated during TLS handshake. Any certificate validation error
including failing the host name check now raises
SSLCertVerificationError
and aborts the handshake with a proper
TLS Alert message. The new exception contains additional information.
Host name validation can be customized with
SSLContext.hostname_checks_common_name
.
(Contributed by Christian Heimes in bpo-31399.)
Nota
The improved host name check requires a libssl implementation compatible with OpenSSL 1.0.2 or 1.1. Consequently, OpenSSL 0.9.8 and 1.0.1 are no longer supported (see Platform Support Removals for more details). The ssl module is mostly compatible with LibreSSL 2.7.2 and newer.
The ssl
module no longer sends IP addresses in SNI TLS extension.
(Contributed by Christian Heimes in bpo-32185.)
match_hostname()
no longer supports partial wildcards like
www*.example.org
.
(Contributed by Mandeep Singh in bpo-23033 and Christian Heimes in
bpo-31399.)
The default cipher suite selection of the ssl
module now uses a blacklist
approach rather than a hard-coded whitelist. Python no longer re-enables
ciphers that have been blocked by OpenSSL security updates. Default cipher
suite selection can be configured at compile time.
(Contributed by Christian Heimes in bpo-31429.)
Validation of server certificates containing internationalized domain names
(IDNs) is now supported. As part of this change, the
SSLSocket.server_hostname
attribute
now stores the expected hostname in A-label form ("xn--pythn-mua.org"
),
rather than the U-label form ("pythön.org"
). (Contributed by
Nathaniel J. Smith and Christian Heimes in bpo-28414.)
The ssl
module has preliminary and experimental support for TLS 1.3 and
OpenSSL 1.1.1. At the time of Python 3.7.0 release, OpenSSL 1.1.1 is still
under development and TLS 1.3 hasn’t been finalized yet. The TLS 1.3
handshake and protocol behaves slightly differently than TLS 1.2 and earlier,
see TLS 1.3.
(Contributed by Christian Heimes in bpo-32947, bpo-20995,
bpo-29136, bpo-30622 and bpo-33618)
SSLSocket
and SSLObject
no longer have a public
constructor. Direct instantiation was never a documented and supported
feature. Instances must be created with SSLContext
methods
wrap_socket()
and wrap_bio()
.
(Contributed by Christian Heimes in bpo-32951)
OpenSSL 1.1 APIs for setting the minimum and maximum TLS protocol version are
available as SSLContext.minimum_version
and SSLContext.maximum_version
.
Supported protocols are indicated by several new flags, such as
HAS_TLSv1_1
.
(Contributed by Christian Heimes in bpo-32609.)
Added ssl.SSLContext.post_handshake_auth
to enable and
ssl.SSLSocket.verify_client_post_handshake()
to initiate TLS 1.3
post-handshake authentication.
(Contributed by Christian Heimes in gh-78851.)
string¶
string.Template
now lets you to optionally modify the regular
expression pattern for braced placeholders and non-braced placeholders
separately. (Contributed by Barry Warsaw in bpo-1198569.)
subprocess¶
The subprocess.run()
function accepts the new capture_output
keyword argument. When true, stdout and stderr will be captured.
This is equivalent to passing subprocess.PIPE
as stdout and
stderr arguments.
(Contributed by Bo Bayles in bpo-32102.)
The subprocess.run
function and the subprocess.Popen
constructor
now accept the text keyword argument as an alias
to universal_newlines.
(Contributed by Andrew Clegg in bpo-31756.)
On Windows the default for close_fds was changed from False
to
True
when redirecting the standard handles. It’s now possible to set
close_fds to true when redirecting the standard handles. See
subprocess.Popen
. This means that close_fds now defaults to
True
on all supported platforms.
(Contributed by Segev Finer in bpo-19764.)
The subprocess module is now more graceful when handling
KeyboardInterrupt
during subprocess.call()
,
subprocess.run()
, or in a Popen
context manager. It now waits a short amount of time for the child
to exit, before continuing the handling of the KeyboardInterrupt
exception.
(Contributed by Gregory P. Smith in bpo-25942.)
sys¶
The new sys.breakpointhook()
hook function is called by the
built-in breakpoint()
.
(Contributed by Barry Warsaw in bpo-31353.)
On Android, the new sys.getandroidapilevel()
returns the build-time
Android API version.
(Contributed by Victor Stinner in bpo-28740.)
The new sys.get_coroutine_origin_tracking_depth()
function returns
the current coroutine origin tracking depth, as set by
the new sys.set_coroutine_origin_tracking_depth()
. asyncio
has been converted to use this new API instead of
the deprecated sys.set_coroutine_wrapper()
.
(Contributed by Nathaniel J. Smith in bpo-32591.)
time¶
PEP 564 adds six new functions with nanosecond resolution to the
time
module:
New clock identifiers have been added:
time.CLOCK_BOOTTIME
(Linux): Identical totime.CLOCK_MONOTONIC
, except it also includes any time that the system is suspended.time.CLOCK_PROF
(FreeBSD, NetBSD and OpenBSD): High-resolution per-process CPU timer.time.CLOCK_UPTIME
(FreeBSD, OpenBSD): Time whose absolute value is the time the system has been running and not suspended, providing accurate uptime measurement.
The new time.thread_time()
and time.thread_time_ns()
functions
can be used to get per-thread CPU time measurements.
(Contributed by Antoine Pitrou in bpo-32025.)
The new time.pthread_getcpuclockid()
function returns the clock ID
of the thread-specific CPU-time clock.
tkinter¶
The new tkinter.ttk.Spinbox
class is now available.
(Contributed by Alan Moore in bpo-32585.)
tracemalloc¶
tracemalloc.Traceback
behaves more like regular tracebacks,
sorting the frames from oldest to most recent.
Traceback.format()
now accepts negative limit, truncating the result to the
abs(limit)
oldest frames. To get the old behaviour, use
the new most_recent_first argument to Traceback.format()
.
(Contributed by Jesse Bakker in bpo-32121.)
types¶
The new WrapperDescriptorType
,
MethodWrapperType
, MethodDescriptorType
,
and ClassMethodDescriptorType
classes are now available.
(Contributed by Manuel Krebber and Guido van Rossum in bpo-29377,
and Serhiy Storchaka in bpo-32265.)
The new types.resolve_bases()
function resolves MRO entries
dynamically as specified by PEP 560.
(Contributed by Ivan Levkivskyi in bpo-32717.)
unicodedata¶
The internal unicodedata
database has been upgraded to use Unicode 11. (Contributed by Benjamin
Peterson.)
unittest¶
The new -k
command-line option allows filtering tests by a name
substring or a Unix shell-like pattern.
For example, python -m unittest -k foo
runs
foo_tests.SomeTest.test_something
, bar_tests.SomeTest.test_foo
,
but not bar_tests.FooTest.test_something
.
(Contributed by Jonas Haag in bpo-32071.)
unittest.mock¶
The sentinel
attributes now preserve their identity
when they are copied
or pickled
. (Contributed by
Serhiy Storchaka in bpo-20804.)
The new seal()
function allows sealing
Mock
instances, which will disallow further creation
of attribute mocks. The seal is applied recursively to all attributes that
are themselves mocks.
(Contributed by Mario Corchero in bpo-30541.)
urllib.parse¶
urllib.parse.quote()
has been updated from RFC 2396 to RFC 3986,
adding ~
to the set of characters that are never quoted by default.
(Contributed by Christian Theune and Ratnadeep Debnath in bpo-16285.)
uu¶
The uu.encode()
function now accepts an optional backtick
keyword argument. When it’s true, zeros are represented by '`'
instead of spaces. (Contributed by Xiang Zhang in bpo-30103.)
uuid¶
The new UUID.is_safe
attribute relays information
from the platform about whether generated UUIDs are generated with a
multiprocessing-safe method.
(Contributed by Barry Warsaw in bpo-22807.)
uuid.getnode()
now prefers universally administered
MAC addresses over locally administered MAC addresses.
This makes a better guarantee for global uniqueness of UUIDs returned
from uuid.uuid1()
. If only locally administered MAC addresses are
available, the first such one found is returned.
(Contributed by Barry Warsaw in bpo-32107.)
avisos¶
The initialization of the default warnings filters has changed as follows:
warnings enabled via command line options (including those for
-b
and the new CPython-specific-X
dev
option) are always passed to the warnings machinery via thesys.warnoptions
attribute.warnings filters enabled via the command line or the environment now have the following order of precedence:
the
BytesWarning
filter for-b
(or-bb
)any filters specified with the
-W
optionany filters specified with the
PYTHONWARNINGS
environment variableany other CPython specific filters (e.g. the
default
filter added for the new-X dev
mode)any implicit filters defined directly by the warnings machinery
in CPython debug builds, all warnings are now displayed by default (the implicit filter list is empty)
(Contributed by Nick Coghlan and Victor Stinner in bpo-20361, bpo-32043, and bpo-32230.)
Deprecation warnings are once again shown by default in single-file scripts and at the interactive prompt. See PEP 565: Mostra DeprecationWarning em __main__ for details. (Contributed by Nick Coghlan in bpo-31975.)
xml¶
As mitigation against DTD and external entity retrieval, the
xml.dom.minidom
and xml.sax
modules no longer process
external entities by default.
(Contributed by Christian Heimes in gh-61441.)
xml.etree¶
ElementPath predicates in the find()
methods can now compare text of the current node with [. = "text"]
,
not only text in children. Predicates also allow adding spaces for
better readability. (Contributed by Stefan Behnel in bpo-31648.)
xmlrpc.server¶
SimpleXMLRPCDispatcher.register_function
can now be used as a decorator. (Contributed by Xiang Zhang in
bpo-7769.)
zipapp¶
Function create_archive()
now accepts an optional filter
argument to allow the user to select which files should be included in the
archive. (Contributed by Irmen de Jong in bpo-31072.)
Function create_archive()
now accepts an optional compressed
argument to generate a compressed archive. A command line option
--compress
has also been added to support compression.
(Contributed by Zhiming Wang in bpo-31638.)
zipfile¶
ZipFile
now accepts the new compresslevel parameter to
control the compression level.
(Contributed by Bo Bayles in bpo-21417.)
Subdirectories in archives created by ZipFile
are now stored in
alphabetical order.
(Contributed by Bernhard M. Wiedemann in bpo-30693.)
Alterações na API C¶
A new API for thread-local storage has been implemented. See PEP 539: Nova API C para armazenamento local de thread for an overview and Thread Specific Storage (TSS) API for a complete reference. (Contributed by Masayuki Yamamoto in bpo-25658.)
The new context variables functionality exposes a number of new C APIs.
The new PyImport_GetModule()
function returns the previously
imported module with the given name.
(Contributed by Eric Snow in bpo-28411.)
The new Py_RETURN_RICHCOMPARE
macro eases writing rich
comparison functions.
(Contributed by Petr Victorin in bpo-23699.)
The new Py_UNREACHABLE
macro can be used to mark unreachable
code paths.
(Contributed by Barry Warsaw in bpo-31338.)
The tracemalloc
now exposes a C API through the new
PyTraceMalloc_Track()
and PyTraceMalloc_Untrack()
functions.
(Contributed by Victor Stinner in bpo-30054.)
The new import__find__load__start()
and
import__find__load__done()
static markers can be used to trace
module imports.
(Contributed by Christian Heimes in bpo-31574.)
The fields name
and doc
of structures
PyMemberDef
, PyGetSetDef
,
PyStructSequence_Field
, PyStructSequence_Desc
,
and wrapperbase
are now of type const char *
rather of
char *
. (Contributed by Serhiy Storchaka in bpo-28761.)
The result of PyUnicode_AsUTF8AndSize()
and PyUnicode_AsUTF8()
is now of type const char *
rather of char *
. (Contributed by Serhiy
Storchaka in bpo-28769.)
The result of PyMapping_Keys()
, PyMapping_Values()
and
PyMapping_Items()
is now always a list, rather than a list or a
tuple. (Contributed by Oren Milman in bpo-28280.)
Added functions PySlice_Unpack()
and PySlice_AdjustIndices()
.
(Contributed by Serhiy Storchaka in bpo-27867.)
PyOS_AfterFork()
is deprecated in favour of the new functions
PyOS_BeforeFork()
, PyOS_AfterFork_Parent()
and
PyOS_AfterFork_Child()
. (Contributed by Antoine Pitrou in
bpo-16500.)
The PyExc_RecursionErrorInst
singleton that was part of the public API
has been removed as its members being never cleared may cause a segfault
during finalization of the interpreter. Contributed by Xavier de Gaye in
bpo-22898 and bpo-30697.
Added C API support for timezones with timezone constructors
PyTimeZone_FromOffset()
and PyTimeZone_FromOffsetAndName()
,
and access to the UTC singleton with PyDateTime_TimeZone_UTC
.
Contributed by Paul Ganssle in bpo-10381.
The type of results of PyThread_start_new_thread()
and
PyThread_get_thread_ident()
, and the id parameter of
PyThreadState_SetAsyncExc()
changed from long to
unsigned long.
(Contributed by Serhiy Storchaka in bpo-6532.)
PyUnicode_AsWideCharString()
now raises a ValueError
if the
second argument is NULL
and the wchar_t* string contains null
characters. (Contributed by Serhiy Storchaka in bpo-30708.)
Changes to the startup sequence and the management of dynamic memory
allocators mean that the long documented requirement to call
Py_Initialize()
before calling most C API functions is now
relied on more heavily, and failing to abide by it may lead to segfaults in
embedding applications. See the Porting to Python 3.7 section in this
document and the Antes da inicialização do Python section in the C API documentation
for more details.
The new PyInterpreterState_GetID()
returns the unique ID for a
given interpreter.
(Contributed by Eric Snow in bpo-29102.)
Py_DecodeLocale()
, Py_EncodeLocale()
now use the UTF-8
encoding when the UTF-8 mode is enabled.
(Contributed by Victor Stinner in bpo-29240.)
PyUnicode_DecodeLocaleAndSize()
and PyUnicode_EncodeLocale()
now use the current locale encoding for surrogateescape
error handler.
(Contributed by Victor Stinner in bpo-29240.)
The start and end parameters of PyUnicode_FindChar()
are
now adjusted to behave like string slices.
(Contributed by Xiang Zhang in bpo-28822.)
Mudanças na construção¶
Support for building --without-threads
has been removed. The
threading
module is now always available.
(Contributed by Antoine Pitrou in bpo-31370.).
A full copy of libffi is no longer bundled for use when building the
_ctypes
module on non-OSX UNIX platforms. An installed copy
of libffi is now required when building _ctypes
on such platforms.
(Contributed by Zachary Ware in bpo-27979.)
The Windows build process no longer depends on Subversion to pull in external
sources, a Python script is used to download zipfiles from GitHub instead.
If Python 3.6 is not found on the system (via py -3.6
), NuGet is used to
download a copy of 32-bit Python for this purpose. (Contributed by Zachary
Ware in bpo-30450.)
The ssl
module requires OpenSSL 1.0.2 or 1.1 compatible libssl.
OpenSSL 1.0.1 has reached end of lifetime on 2016-12-31 and is no longer
supported. LibreSSL is temporarily not supported as well. LibreSSL releases
up to version 2.6.4 are missing required OpenSSL 1.0.2 APIs.
Otimizações¶
The overhead of calling many methods of various standard library classes
implemented in C has been significantly reduced by porting more code
to use the METH_FASTCALL
convention.
(Contributed by Victor Stinner in bpo-29300, bpo-29507,
bpo-29452, and bpo-29286.)
Various optimizations have reduced Python startup time by 10% on Linux and up to 30% on macOS. (Contributed by Victor Stinner, INADA Naoki in bpo-29585, and Ivan Levkivskyi in bpo-31333.)
Method calls are now up to 20% faster due to the bytecode changes which avoid creating bound method instances. (Contributed by Yury Selivanov and INADA Naoki in bpo-26110.)
The asyncio
module received a number of notable optimizations for
commonly used functions:
The
asyncio.get_event_loop()
function has been reimplemented in C to make it up to 15 times faster. (Contributed by Yury Selivanov in bpo-32296.)asyncio.Future
callback management has been optimized. (Contributed by Yury Selivanov in bpo-32348.)asyncio.gather()
is now up to 15% faster. (Contributed by Yury Selivanov in bpo-32355.)asyncio.sleep()
is now up to 2 times faster when the delay argument is zero or negative. (Contributed by Andrew Svetlov in bpo-32351.)The performance overhead of asyncio debug mode has been reduced. (Contributed by Antoine Pitrou in bpo-31970.)
As a result of PEP 560 work, the import time
of typing
has been reduced by a factor of 7, and many typing operations
are now faster.
(Contributed by Ivan Levkivskyi in bpo-32226.)
sorted()
and list.sort()
have been optimized for common cases
to be up to 40-75% faster.
(Contributed by Elliot Gorokhovsky in bpo-28685.)
dict.copy()
is now up to 5.5 times faster.
(Contributed by Yury Selivanov in bpo-31179.)
hasattr()
and getattr()
are now about 4 times faster when
name is not found and obj does not override object.__getattr__()
or object.__getattribute__()
.
(Contributed by INADA Naoki in bpo-32544.)
Searching for certain Unicode characters (like Ukrainian capital “Є”) in a string was up to 25 times slower than searching for other characters. It is now only 3 times slower in the worst case. (Contributed by Serhiy Storchaka in bpo-24821.)
The collections.namedtuple()
factory has been reimplemented to
make the creation of named tuples 4 to 6 times faster.
(Contributed by Jelle Zijlstra with further improvements by INADA Naoki,
Serhiy Storchaka, and Raymond Hettinger in bpo-28638.)
date.fromordinal()
and date.fromtimestamp()
are now up to
30% faster in the common case.
(Contributed by Paul Ganssle in bpo-32403.)
The os.fwalk()
function is now up to 2 times faster thanks to
the use of os.scandir()
.
(Contributed by Serhiy Storchaka in bpo-25996.)
The speed of the shutil.rmtree()
function has been improved by
20–40% thanks to the use of the os.scandir()
function.
(Contributed by Serhiy Storchaka in bpo-28564.)
Optimized case-insensitive matching and searching of regular
expressions
. Searching some patterns can now be up to 20 times faster.
(Contributed by Serhiy Storchaka in bpo-30285.)
re.compile()
now converts flags
parameter to int object if
it is RegexFlag
. It is now as fast as Python 3.5, and faster than
Python 3.6 by about 10% depending on the pattern.
(Contributed by INADA Naoki in bpo-31671.)
The modify()
methods of classes
selectors.EpollSelector
, selectors.PollSelector
and selectors.DevpollSelector
may be around 10% faster under
heavy loads. (Contributed by Giampaolo Rodola’ in bpo-30014)
Constant folding has been moved from the peephole optimizer to the new AST optimizer, which is able perform optimizations more consistently. (Contributed by Eugene Toder and INADA Naoki in bpo-29469 and bpo-11549.)
Most functions and methods in abc
have been rewritten in C.
This makes creation of abstract base classes, and calling isinstance()
and issubclass()
on them 1.5x faster. This also reduces Python
start-up time by up to 10%. (Contributed by Ivan Levkivskyi and INADA Naoki
in bpo-31333)
Significant speed improvements to alternate constructors for
datetime.date
and datetime.datetime
by using fast-path
constructors when not constructing subclasses. (Contributed by Paul Ganssle
in bpo-32403)
The speed of comparison of array.array
instances has been
improved considerably in certain cases. It is now from 10x to 70x faster
when comparing arrays holding values of the same integer type.
(Contributed by Adrian Wielgosik in bpo-24700.)
The math.erf()
and math.erfc()
functions now use the (faster)
C library implementation on most platforms.
(Contributed by Serhiy Storchaka in bpo-26121.)
Outras mudanças na implementação do CPython¶
Trace hooks may now opt out of receiving the
line
and opt into receiving theopcode
events from the interpreter by setting the corresponding newf_trace_lines
andf_trace_opcodes
attributes on the frame being traced. (Contributed by Nick Coghlan in bpo-31344.)Fixed some consistency problems with namespace package module attributes. Namespace module objects now have an
__file__
that is set toNone
(previously unset), and their__spec__.origin
is also set toNone
(previously the string"namespace"
). See bpo-32305. Also, the namespace module object’s__spec__.loader
is set to the same value as__loader__
(previously, the former was set toNone
). See bpo-32303.The
locals()
dictionary now displays in the lexical order that variables were defined. Previously, the order was undefined. (Contributed by Raymond Hettinger in bpo-32690.)The
distutils
upload
command no longer tries to change CR end-of-line characters to CRLF. This fixes a corruption issue with sdists that ended with a byte equivalent to CR. (Contributed by Bo Bayles in bpo-32304.)
Comportamento do Python descontinuado¶
Yield expressions (both yield
and yield from
clauses) are now deprecated
in comprehensions and generator expressions (aside from the iterable expression
in the leftmost for
clause). This ensures that comprehensions
always immediately return a container of the appropriate type (rather than
potentially returning a generator iterator object), while generator
expressions won’t attempt to interleave their implicit output with the output
from any explicit yield expressions. In Python 3.7, such expressions emit
DeprecationWarning
when compiled, in Python 3.8 this will be a
SyntaxError
.
(Contributed by Serhiy Storchaka in bpo-10544.)
Returning a subclass of complex
from object.__complex__()
is
deprecated and will be an error in future Python versions. This makes
__complex__()
consistent with object.__int__()
and
object.__float__()
.
(Contributed by Serhiy Storchaka in bpo-28894.)
Deprecated Python modules, functions and methods¶
aifc¶
aifc.openfp()
has been deprecated and will be removed in Python 3.9.
Use aifc.open()
instead.
(Contributed by Brian Curtin in bpo-31985.)
asyncio¶
Support for directly await
-ing instances of asyncio.Lock
and
other asyncio synchronization primitives has been deprecated. An
asynchronous context manager must be used in order to acquire and release
the synchronization resource.
(Contributed by Andrew Svetlov in bpo-32253.)
The asyncio.Task.current_task()
and asyncio.Task.all_tasks()
methods have been deprecated.
(Contributed by Andrew Svetlov in bpo-32250.)
collections¶
In Python 3.8, the abstract base classes in collections.abc
will no
longer be exposed in the regular collections
module. This will help
create a clearer distinction between the concrete classes and the abstract
base classes.
(Contributed by Serhiy Storchaka in bpo-25988.)
dbm¶
dbm.dumb
now supports reading read-only files and no longer writes the
index file when it is not changed. A deprecation warning is now emitted
if the index file is missing and recreated in the 'r'
and 'w'
modes (this will be an error in future Python releases).
(Contributed by Serhiy Storchaka in bpo-28847.)
enum¶
In Python 3.8, attempting to check for non-Enum objects in Enum
classes will raise a TypeError
(e.g. 1 in Color
); similarly,
attempting to check for non-Flag objects in a Flag
member will
raise TypeError
(e.g. 1 in Perm.RW
); currently, both operations
return False
instead.
(Contributed by Ethan Furman in bpo-33217.)
gettext¶
Using non-integer value for selecting a plural form in gettext
is
now deprecated. It never correctly worked. (Contributed by Serhiy Storchaka
in bpo-28692.)
importlib¶
Methods
MetaPathFinder.find_module()
(replaced by
MetaPathFinder.find_spec()
)
and
PathEntryFinder.find_loader()
(replaced by
PathEntryFinder.find_spec()
)
both deprecated in Python 3.4 now emit DeprecationWarning
.
(Contributed by Matthias Bussonnier in bpo-29576.)
The importlib.abc.ResourceLoader
ABC has been deprecated in
favour of importlib.abc.ResourceReader
.
locale¶
locale.format()
has been deprecated, use locale.format_string()
instead. (Contributed by Garvit in bpo-10379.)
macpath¶
The macpath
is now deprecated and will be removed in Python 3.8.
(Contributed by Chi Hsuan Yen in bpo-9850.)
threading¶
dummy_threading
and _dummy_thread
have been deprecated. It is
no longer possible to build Python with threading disabled.
Use threading
instead.
(Contributed by Antoine Pitrou in bpo-31370.)
socket¶
The silent argument value truncation in socket.htons()
and
socket.ntohs()
has been deprecated. In future versions of Python,
if the passed argument is larger than 16 bits, an exception will be raised.
(Contributed by Oren Milman in bpo-28332.)
ssl¶
ssl.wrap_socket()
is deprecated. Use
ssl.SSLContext.wrap_socket()
instead.
(Contributed by Christian Heimes in bpo-28124.)
sunau¶
sunau.openfp()
has been deprecated and will be removed in Python 3.9.
Use sunau.open()
instead.
(Contributed by Brian Curtin in bpo-31985.)
sys¶
Deprecated sys.set_coroutine_wrapper()
and
sys.get_coroutine_wrapper()
.
The undocumented sys.callstats()
function has been deprecated and
will be removed in a future Python version.
(Contributed by Victor Stinner in bpo-28799.)
wave¶
wave.openfp()
has been deprecated and will be removed in Python 3.9.
Use wave.open()
instead.
(Contributed by Brian Curtin in bpo-31985.)
Deprecated functions and types of the C API¶
Function PySlice_GetIndicesEx()
is deprecated and replaced with
a macro if Py_LIMITED_API
is not set or set to a value in the range
between 0x03050400
and 0x03060000
(not inclusive), or is 0x03060100
or higher. (Contributed by Serhiy Storchaka in bpo-27867.)
PyOS_AfterFork()
has been deprecated. Use PyOS_BeforeFork()
,
PyOS_AfterFork_Parent()
or PyOS_AfterFork_Child()
instead.
(Contributed by Antoine Pitrou in bpo-16500.)
Platform Support Removals¶
FreeBSD 9 and older are no longer officially supported.
For full Unicode support, including within extension modules, *nix platforms are now expected to provide at least one of
C.UTF-8
(full locale),C.utf8
(full locale) orUTF-8
(LC_CTYPE
-only locale) as an alternative to the legacyASCII
-basedC
locale.OpenSSL 0.9.8 and 1.0.1 are no longer supported, which means building CPython 3.7 with SSL/TLS support on older platforms still using these versions requires custom build options that link to a more recent version of OpenSSL.
Notably, this issue affects the Debian 8 (aka “jessie”) and Ubuntu 14.04 (aka “Trusty”) LTS Linux distributions, as they still use OpenSSL 1.0.1 by default.
Debian 9 (“stretch”) and Ubuntu 16.04 (“xenial”), as well as recent releases of other LTS Linux releases (e.g. RHEL/CentOS 7.5, SLES 12-SP3), use OpenSSL 1.0.2 or later, and remain supported in the default build configuration.
CPython’s own CI configuration file provides an example of using the SSL compatibility testing infrastructure in CPython’s test suite to build and link against OpenSSL 1.1.0 rather than an outdated system provided OpenSSL.
Remoção de APIs e recursos¶
The following features and APIs have been removed from Python 3.7:
The
os.stat_float_times()
function has been removed. It was introduced in Python 2.3 for backward compatibility with Python 2.2, and was deprecated since Python 3.1.Unknown escapes consisting of
'\'
and an ASCII letter in replacement templates forre.sub()
were deprecated in Python 3.5, and will now cause an error.Removed support of the exclude argument in
tarfile.TarFile.add()
. It was deprecated in Python 2.7 and 3.2. Use the filter argument instead.The
ntpath.splitunc()
function was deprecated in Python 3.1, and has now been removed. Usesplitdrive()
instead.collections.namedtuple()
no longer supports the verbose parameter or_source
attribute which showed the generated source code for the named tuple class. This was part of an optimization designed to speed-up class creation. (Contributed by Jelle Zijlstra with further improvements by INADA Naoki, Serhiy Storchaka, and Raymond Hettinger in bpo-28638.)Functions
bool()
,float()
,list()
andtuple()
no longer take keyword arguments. The first argument ofint()
can now be passed only as positional argument.Removed previously deprecated in Python 2.4 classes
Plist
,Dict
and_InternalDict
in theplistlib
module. Dict values in the result of functionsreadPlist()
andreadPlistFromBytes()
are now normal dicts. You no longer can use attribute access to access items of these dictionaries.The
asyncio.windows_utils.socketpair()
function has been removed. Use thesocket.socketpair()
function instead, it is available on all platforms since Python 3.5.asyncio.windows_utils.socketpair
was just an alias tosocket.socketpair
on Python 3.5 and newer.asyncio
no longer exports theselectors
and_overlapped
modules asasyncio.selectors
andasyncio._overlapped
. Replacefrom asyncio import selectors
withimport selectors
.Direct instantiation of
ssl.SSLSocket
andssl.SSLObject
objects is now prohibited. The constructors were never documented, tested, or designed as public constructors. Users were supposed to usessl.wrap_socket()
orssl.SSLContext
. (Contributed by Christian Heimes in bpo-32951.)The unused
distutils
install_misc
command has been removed. (Contributed by Eric N. Vander Weele in bpo-29218.)
Module Removals¶
The fpectl
module has been removed. It was never enabled by
default, never worked correctly on x86-64, and it changed the Python
ABI in ways that caused unexpected breakage of C extensions.
(Contributed by Nathaniel J. Smith in bpo-29137.)
Windows-only Changes¶
The python launcher, (py.exe), can accept 32 & 64 bit specifiers without
having to specify a minor version as well. So py -3-32
and py -3-64
become valid as well as py -3.7-32
, also the -m-64 and -m.n-64 forms
are now accepted to force 64 bit python even if 32 bit would have otherwise
been used. If the specified version is not available py.exe will error exit.
(Contributed by Steve Barnes in bpo-30291.)
The launcher can be run as py -0
to produce a list of the installed pythons,
with default marked with an asterisk. Running py -0p
will include the paths.
If py is run with a version specifier that cannot be matched it will also print
the short form list of available specifiers.
(Contributed by Steve Barnes in bpo-30362.)
Porting to Python 3.7¶
Esta seção lista as alterações descritas anteriormente e outras correções que podem exigir alterações no seu código.
Changes in Python Behavior¶
async
andawait
names are now reserved keywords. Code using these names as identifiers will now raise aSyntaxError
. (Contributed by Jelle Zijlstra in bpo-30406.)PEP 479 is enabled for all code in Python 3.7, meaning that
StopIteration
exceptions raised directly or indirectly in coroutines and generators are transformed intoRuntimeError
exceptions. (Contributed by Yury Selivanov in bpo-32670.)object.__aiter__()
methods can no longer be declared as asynchronous. (Contributed by Yury Selivanov in bpo-31709.)Due to an oversight, earlier Python versions erroneously accepted the following syntax:
f(1 for x in [1],) class C(1 for x in [1]): pass
Python 3.7 now correctly raises a
SyntaxError
, as a generator expression always needs to be directly inside a set of parentheses and cannot have a comma on either side, and the duplication of the parentheses can be omitted only on calls. (Contributed by Serhiy Storchaka in bpo-32012 and bpo-32023.)When using the
-m
switch, the initial working directory is now added tosys.path
, rather than an empty string (which dynamically denoted the current working directory at the time of each import). Any programs that are checking for the empty string, or otherwise relying on the previous behaviour, will need to be updated accordingly (e.g. by also checking foros.getcwd()
oros.path.dirname(__main__.__file__)
, depending on why the code was checking for the empty string in the first place).
Alterações na API Python¶
socketserver.ThreadingMixIn.server_close()
now waits until all non-daemon threads complete. Set the newsocketserver.ThreadingMixIn.block_on_close
class attribute toFalse
to get the pre-3.7 behaviour. (Contributed by Victor Stinner in bpo-31233 and bpo-33540.)socketserver.ForkingMixIn.server_close()
now waits until all child processes complete. Set the newsocketserver.ForkingMixIn.block_on_close
class attribute toFalse
to get the pre-3.7 behaviour. (Contributed by Victor Stinner in bpo-31151 and bpo-33540.)The
locale.localeconv()
function now temporarily sets theLC_CTYPE
locale to the value ofLC_NUMERIC
in some cases. (Contributed by Victor Stinner in bpo-31900.)pkgutil.walk_packages()
now raises aValueError
if path is a string. Previously an empty list was returned. (Contributed by Sanyam Khurana in bpo-24744.)A format string argument for
string.Formatter.format()
is now positional-only. Passing it as a keyword argument was deprecated in Python 3.5. (Contributed by Serhiy Storchaka in bpo-29193.)Attributes
key
,value
andcoded_value
of classhttp.cookies.Morsel
are now read-only. Assigning to them was deprecated in Python 3.5. Use theset()
method for setting them. (Contributed by Serhiy Storchaka in bpo-29192.)The mode argument of
os.makedirs()
no longer affects the file permission bits of newly created intermediate-level directories. To set their file permission bits you can set the umask before invokingmakedirs()
. (Contributed by Serhiy Storchaka in bpo-19930.)The
struct.Struct.format
type is nowstr
instead ofbytes
. (Contributed by Victor Stinner in bpo-21071.)cgi.parse_multipart()
now accepts the encoding and errors arguments and returns the same results asFieldStorage
: for non-file fields, the value associated to a key is a list of strings, not bytes. (Contributed by Pierre Quentel in bpo-29979.)Due to internal changes in
socket
, callingsocket.fromshare()
on a socket created bysocket.share
in older Python versions is not supported.repr
forBaseException
has changed to not include the trailing comma. Most exceptions are affected by this change. (Contributed by Serhiy Storchaka in bpo-30399.)repr
fordatetime.timedelta
has changed to include the keyword arguments in the output. (Contributed by Utkarsh Upadhyay in bpo-30302.)Because
shutil.rmtree()
is now implemented using theos.scandir()
function, the user specified handler onerror is now called with the first argumentos.scandir
instead ofos.listdir
when listing the directory is failed.Support for nested sets and set operations in regular expressions as in Unicode Technical Standard #18 might be added in the future. This would change the syntax. To facilitate this future change a
FutureWarning
will be raised in ambiguous cases for the time being. That include sets starting with a literal'['
or containing literal character sequences'--'
,'&&'
,'~~'
, and'||'
. To avoid a warning, escape them with a backslash. (Contributed by Serhiy Storchaka in bpo-30349.)The result of splitting a string on a
regular expression
that could match an empty string has been changed. For example splitting onr'\s*'
will now split not only on whitespaces as it did previously, but also on empty strings before all non-whitespace characters and just before the end of the string. The previous behavior can be restored by changing the pattern tor'\s+'
. AFutureWarning
was emitted for such patterns since Python 3.5.For patterns that match both empty and non-empty strings, the result of searching for all matches may also be changed in other cases. For example in the string
'a\n\n'
, the patternr'(?m)^\s*?$'
will not only match empty strings at positions 2 and 3, but also the string'\n'
at positions 2–3. To match only blank lines, the pattern should be rewritten asr'(?m)^[^\S\n]*$'
.re.sub()
now replaces empty matches adjacent to a previous non-empty match. For examplere.sub('x*', '-', 'abxd')
returns now'-a-b--d-'
instead of'-a-b-d-'
(the first minus between ‘b’ and ‘d’ replaces ‘x’, and the second minus replaces an empty string between ‘x’ and ‘d’).(Contributed by Serhiy Storchaka in bpo-25054 and bpo-32308.)
Change
re.escape()
to only escape regex special characters instead of escaping all characters other than ASCII letters, numbers, and'_'
. (Contributed by Serhiy Storchaka in bpo-29995.)tracemalloc.Traceback
frames are now sorted from oldest to most recent to be more consistent withtraceback
. (Contributed by Jesse Bakker in bpo-32121.)On OSes that support
socket.SOCK_NONBLOCK
orsocket.SOCK_CLOEXEC
bit flags, thesocket.type
no longer has them applied. Therefore, checks likeif sock.type == socket.SOCK_STREAM
work as expected on all platforms. (Contributed by Yury Selivanov in bpo-32331.)On Windows the default for the close_fds argument of
subprocess.Popen
was changed fromFalse
toTrue
when redirecting the standard handles. If you previously depended on handles being inherited when usingsubprocess.Popen
with standard io redirection, you will have to passclose_fds=False
to preserve the previous behaviour, or useSTARTUPINFO.lpAttributeList
.importlib.machinery.PathFinder.invalidate_caches()
– which implicitly affectsimportlib.invalidate_caches()
– now deletes entries insys.path_importer_cache
which are set toNone
. (Contributed by Brett Cannon in bpo-33169.)In
asyncio
,loop.sock_recv()
,loop.sock_sendall()
,loop.sock_accept()
,loop.getaddrinfo()
,loop.getnameinfo()
have been changed to be proper coroutine methods to match their documentation. Previously, these methods returnedasyncio.Future
instances. (Contributed by Yury Selivanov in bpo-32327.)asyncio.Server.sockets
now returns a copy of the internal list of server sockets, instead of returning it directly. (Contributed by Yury Selivanov in bpo-32662.)Struct.format
is now astr
instance instead of abytes
instance. (Contributed by Victor Stinner in bpo-21071.)argparse
subparsers can now be made mandatory by passingrequired=True
toArgumentParser.add_subparsers()
. (Contributed by Anthony Sottile in bpo-26510.)ast.literal_eval()
is now stricter. Addition and subtraction of arbitrary numbers are no longer allowed. (Contributed by Serhiy Storchaka in bpo-31778.)Calendar.itermonthdates
will now consistently raise an exception when a date falls outside of the0001-01-01
through9999-12-31
range. To support applications that cannot tolerate such exceptions, the newCalendar.itermonthdays3
andCalendar.itermonthdays4
can be used. The new methods return tuples and are not restricted by the range supported bydatetime.date
. (Contributed by Alexander Belopolsky in bpo-28292.)collections.ChainMap
now preserves the order of the underlying mappings. (Contributed by Raymond Hettinger in bpo-32792.)The
submit()
method ofconcurrent.futures.ThreadPoolExecutor
andconcurrent.futures.ProcessPoolExecutor
now raises aRuntimeError
if called during interpreter shutdown. (Contributed by Mark Nemec in bpo-33097.)The
configparser.ConfigParser
constructor now usesread_dict()
to process the default values, making its behavior consistent with the rest of the parser. Non-string keys and values in the defaults dictionary are now being implicitly converted to strings. (Contributed by James Tocknell in bpo-23835.)Several undocumented internal imports were removed. One example is that
os.errno
is no longer available; useimport errno
directly instead. Note that such undocumented internal imports may be removed any time without notice, even in micro version releases.
Alterações na API C¶
The function PySlice_GetIndicesEx()
is considered unsafe for
resizable sequences. If the slice indices are not instances of int
,
but objects that implement the __index__()
method, the sequence can be
resized after passing its length to PySlice_GetIndicesEx()
. This
can lead to returning indices out of the length of the sequence. For
avoiding possible problems use new functions PySlice_Unpack()
and
PySlice_AdjustIndices()
.
(Contributed by Serhiy Storchaka in bpo-27867.)
Alterações de bytecode do CPython¶
There are two new opcodes: LOAD_METHOD
and CALL_METHOD
.
(Contributed by Yury Selivanov and INADA Naoki in bpo-26110.)
The STORE_ANNOTATION
opcode has been removed.
(Contributed by Mark Shannon in bpo-32550.)
Windows-only Changes¶
The file used to override sys.path
is now called
<python-executable>._pth
instead of 'sys.path'
.
See Encontrando módulos for more information.
(Contributed by Steve Dower in bpo-28137.)
Other CPython implementation changes¶
In preparation for potential future changes to the public CPython runtime initialization API (see PEP 432 for an initial, but somewhat outdated, draft), CPython’s internal startup and configuration management logic has been significantly refactored. While these updates are intended to be entirely transparent to both embedding applications and users of the regular CPython CLI, they’re being mentioned here as the refactoring changes the internal order of various operations during interpreter startup, and hence may uncover previously latent defects, either in embedding applications, or in CPython itself. (Initially contributed by Nick Coghlan and Eric Snow as part of bpo-22257, and further updated by Nick, Eric, and Victor Stinner in a number of other issues). Some known details affected:
PySys_AddWarnOptionUnicode()
is not currently usable by embedding applications due to the requirement to create a Unicode object prior to callingPy_Initialize
. UsePySys_AddWarnOption()
instead.warnings filters added by an embedding application with
PySys_AddWarnOption()
should now more consistently take precedence over the default filters set by the interpreter
Due to changes in the way the default warnings filters are configured,
setting Py_BytesWarningFlag
to a value greater than one is no longer
sufficient to both emit BytesWarning
messages and have them converted
to exceptions. Instead, the flag must be set (to cause the warnings to be
emitted in the first place), and an explicit error::BytesWarning
warnings filter added to convert them to exceptions.
Due to a change in the way docstrings are handled by the compiler, the
implicit return None
in a function body consisting solely of a docstring
is now marked as occurring on the same line as the docstring, not on the
function’s header line.
The current exception state has been moved from the frame object to the co-routine. This simplified the interpreter and fixed a couple of obscure bugs caused by having swap exception state when entering or exiting a generator. (Contributed by Mark Shannon in bpo-25612.)
Notable changes in Python 3.7.1¶
Starting in 3.7.1, Py_Initialize()
now consistently reads and respects
all of the same environment settings as Py_Main()
(in earlier Python
versions, it respected an ill-defined subset of those environment variables,
while in Python 3.7.0 it didn’t read any of them due to bpo-34247). If
this behavior is unwanted, set Py_IgnoreEnvironmentFlag
to 1 before
calling Py_Initialize()
.
In 3.7.1 the C API for Context Variables
was updated to use
PyObject
pointers. See also bpo-34762.
In 3.7.1 the tokenize
module now implicitly emits a NEWLINE
token
when provided with input that does not have a trailing new line. This behavior
now matches what the C tokenizer does internally.
(Contributed by Ammar Askar in bpo-33899.)
Notable changes in Python 3.7.2¶
In 3.7.2, venv
on Windows no longer copies the original binaries, but
creates redirector scripts named python.exe
and pythonw.exe
instead.
This resolves a long standing issue where all virtual environments would have
to be upgraded or recreated with each Python update. However, note that this
release will still require recreation of virtual environments in order to get
the new scripts.
Notable changes in Python 3.7.6¶
Devido a significativas preocupações de segurança, o parâmetro reuse_address de asyncio.loop.create_datagram_endpoint()
não é mais suportado. Isso ocorre devido ao comportamento da opção de soquete SO_REUSEADDR
no UDP. Para mais detalhes, consulte a documentação de loop.create_datagram_endpoint()
. (Contribuição de Kyle Stanley, Antoine Pitrou e Yury Selivanov em bpo-37228.)
Notable changes in Python 3.7.10¶
Versões anteriores do Python permitiam o uso de ;
e &
como separadores de parâmetros de consulta nas funções urllib.parse.parse_qs()
e urllib.parse.parse_qsl()
. Devido a questões de segurança, e em conformidade com as recomendações mais recentes do W3C, isso foi alterado para permitir apenas uma única chave separadora, com &
como padrão. Esta mudança também afeta as funções cgi.parse()
e cgi.parse_multipart()
já que elas usam as funções afetadas internamente. Para obter mais detalhes, consulte sua respectiva documentação. (Contribuição de Adam Goldschmidt, Senthil Kumaran e Ken Jin em bpo-42967.)
Notable changes in Python 3.7.11¶
Uma correção de segurança altera o comportamento ftplib.FTP
para não confiar no endereço IPv4 enviado do servidor remoto ao configurar um canal de dados passivo. Em vez disso, reutilizamos o endereço IP do servidor ftp. Para códigos incomuns que requerem o comportamento antigo, defina um atributo trust_server_pasv_ipv4_address
em sua instância de FTP para True
. (Veja gh-87451)
The presence of newline or tab characters in parts of a URL allows for some
forms of attacks. Following the WHATWG specification that updates RFC 3986,
ASCII newline \n
, \r
and tab \t
characters are stripped from the
URL by the parser urllib.parse()
preventing such attacks. The removal
characters are controlled by a new module level variable
urllib.parse._UNSAFE_URL_BYTES_TO_REMOVE
. (See gh-88048)
Notable security feature in 3.7.14¶
Converter entre int
e str
em bases diferentes de 2 (binário), 4, 8 (octal), 16 (hexadecimal) ou 32 como base 10 (decimal) agora levanta uma exceção ValueError
se o número de dígitos em forma de string estiver acima de um limite para evitar possíveis ataques de negação de serviço devido à complexidade algorítmica. Esta é uma mitigação para CVE 2020-10735. Este limite pode ser configurado ou desabilitado por variável de ambiente, sinalizador de linha de comando ou APIs de sys
. Veja a documentação de limitação de comprimento de conversão de string inteira. O limite padrão é de 4300 dígitos em forma de string.