python / python/cpython

Keyword typo suggestions differ between file and string tokenizers

Aberta
#156,047 4 comentários 0 reações 0 responsáveis Ver no GitHub

Ninguém assumiu esta issue ainda.

3.14 3.15 3.16 interpreter-core topic-parser type-bug
Linguagem predominante
Python
Estrelas
77.2k
Forks
36k
Métricas de merge de PRs
Métricas de PR pendentes

Descrição

Bug report

Bug description:

Keyword-typo SyntaxError suggestions depend on whether CPython processes the same source using the file tokenizer or the string tokenizer.

Create t.py containing:

a=b=c=d=e=f=g=h=i=0
def fn():
    retrun True

Running the file directly:

$ python t.py

uses the file-tokenizer path and produces the helpful diagnostic:

  File ".../t.py", line 3
    retrun True
    ^^^^^^
SyntaxError: invalid syntax. Did you mean 'return'?

Running the same file as a module:

$ python -m t

uses the string-tokenizer path and produces:

  File ".../t.py", line 3
    retrun True
           ^^^^
SyntaxError: invalid syntax

The same discrepancy is visible in the default PyREPL-based REPL.

Pasting the complete block as one input:

a=b=c=d=e=f=g=h=i=0
def fn():
    retrun True

produces the generic error:

  File "<python-input-0>", line 3
    retrun True
           ^^^^
SyntaxError: invalid syntax

Entering and submitting the assignment separately, followed by the function:

a=b=c=d=e=f=g=h=i=0
def fn():
    retrun True

produces:

  File "<python-input-2>", line 2
    retrun True
    ^^^^^^
SyntaxError: invalid syntax. Did you mean 'return'?

I would expect the same source code to produce the same keyword suggestion regardless of whether it is:

  • executed as a file with python t.py;
  • loaded as a module with python -m t;
  • pasted into PyREPL as one block; or
  • entered into PyREPL statement by statement.

This appears related to the keyword-typo suggestions added in #132449.

traceback.TracebackException._find_keyword_typos() treats the two source paths differently:

  • When the source is loaded from the filename, tokens outside the reported error line are skipped before consuming the token-search budget.
  • When the source is included directly in the SyntaxError metadata, all non-keyword NAME tokens in the extracted source fragment consume that budget.

The search is limited to ten such tokens. In this example, a through i account for nine tokens and fn is the tenth, so the string-source path stops before examining retrun. The file-source path skips those earlier lines and finds the typo.

One possible approach would be to prioritize tokens on the reported error line for both source paths, and only then search the surrounding source fragment. That would preserve the existing work limit while avoiding this tokenizer-dependent result.

CPython versions tested on:

CPython main branch, 3.15, 3.14

Operating systems tested on:

macOS

Linked PRs
  • gh-156087

Guia de contribuição

Abrir o guia de contribuição

Primeiros passos

  1. Leia a issue inteira e depois o guia de contribuição do projeto.
  2. Comente na issue dizendo que vai assumir — evita que duas pessoas façam o mesmo trabalho.
  3. Faça um fork do repositório e trabalhe em uma branch.
  4. Abra um pull request que referencie o número da issue.

Direção de pesquisa

Comece em traceback.TracebackException._find_keyword_typos(), comparando seus caminhos de filename e metadados de SyntaxError e o orçamento de dez tokens descrito aqui. Reproduza os quatro modos de execução acima; está concluído quando a mesma fonte produz a mesma sugestão de palavra-chave na execução de arquivo, no carregamento de módulo e em ambas as formas de entrada do PyREPL.

Escrita pelo modelo de indexação a partir do texto da issue.

Avaliação

Stack de tecnologia
python
Domínio
compilers
Tipo de issue
Bug
Dificuldade
3/5
Tempo estimado
1-2 dias
Status de atividade
Estagnada
Clareza
Claramente especificada
Facilidade para iniciantes
25/100

Receba novas issues na sua caixa de entrada

Um resumo curto de issues do GitHub para quem está começando.