python / python/mypy

Redefinition without reassignment doesn't check existing value

Offen
#12,866 3 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-variable-scope
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

With --allow-redefinition, mypy allows a variable to be redefined, without checking that the existing value is the correct type.

a: str = "foo"
print(a)  # value needs to be used before redefinition
a: int  # but it is really still str
if a > 1:
    ...

https://mypy-play.net/?mypy=latest&python=3.10&flags=allow-redefinition&gist=79d1e9219d66da441050ba730a7c2842

Expected Behaviour

In this example, mypy should detect that a is still a str, and not allow this redefinition.

It could treat the redefinition as though it is a new variable, being assigned the value of the existing one. That would result in an error like:
error: Incompatible types in assignment (expression has type "str", variable has type "int")

Or it could be a new error, like:
error: Redefinition incompatible with existing type (existing type "str", new type "int")

Actual Behaviour

mypy:

Success: no issues found in 1 source file

python:

TypeError: '>' not supported between instances of 'str' and 'int'

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 damit, das Beispiel aus dem verlinkten mypy-play.net-Lauf mit --allow-redefinition zu reproduzieren, und verfolge dann, wie mypy annotierte Neudefinitionen verarbeitet. Die Arbeit ist abgeschlossen, wenn der vorhandene str-Wert anhand der späteren int-Annotation geprüft wird und mypy statt eines Erfolgs einen entsprechenden Fehler meldet.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
devtools
Issue-Typ
Bug
Schwierigkeit
4/5
Geschätzter Aufwand
3-5 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.