python / python/cpython

tokenize: `e.offset` on `IndentationError` is not set correctly

Offen
#153,837 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

3.14 3.15 3.16 interpreter-core topic-parser type-bug
Vorherrschende Sprache
Python
Sterne
77.2k
Forks
35.9k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug report

Bug description:
import io, tokenize

input_s = """
def foo():
    x = 1
   x = "some_very_long_expression"
"""
try:
    list(tokenize.generate_tokens(io.StringIO(input_s).readline))
except IndentationError as e:
    print(f"{e.offset = }")

The line x = "some_very_long_expression" is indented with 3 spaces instead of 4, so we get an error.
We would expect the offset to be around 3, since that is where the issue is.
On python 3.12+, the offset is instead 35, equal to the length of the line + 1.

This appears to be caused by the refactor of tokenize done in 3.12 for PEP 701
Potentially related to https://github.com/python/cpython/issues/84515
Funnily enough, the exact same thing seems to have happened around 3.8 https://github.com/python/cpython/issues/75676

Tested versions:

Version e.offset
3.11.15 3
3.12.13 35
3.13.13 35
3.14.4 35
3.15.0b1 35

Testing command:
nix-shell -p python311 --run "python --version && python tmp.py"
(and replace 311 by 312, 313, etc)

CPython versions tested on:

3.15

Operating systems tested on:

Linux

Linked PRs
  • gh-154281

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Beginne mit tokenize.generate_tokens und reproduziere das bereitgestellte IndentationError-Beispiel über die aufgeführten Python-Versionen hinweg. Verfolge, wie der Tokenizer IndentationError konstruiert, und vergleiche den Offset mit dem Verhalten von Python 3.11. Als erledigt gilt es, wenn die falsch eingerückte Zeile einen Offset nahe 3 meldet und eine Regressionstestabdeckung für das Beispiel vorhanden ist.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers
Issue-Typ
Bug
Schwierigkeit
3/5
Geschätzter Aufwand
1-2 Tage
Aktivitätsstatus
Veraltet
Klarheit
Größtenteils klar
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.