python / python/mypy

"Cannot determine type" if first assignment to attribute is unreachable

Offen
#9,709 0 Kommentare 1 Reaktion 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-inference topic-reachability
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

To Reproduce

Run mypy on the following code:

class C:
    def __init__(self, a: str) -> None:
        if a is None:
            self.x = 123
        else:
            self.x = 456

It will output:

testcase.py:6: error: Cannot determine type of 'x'

Line 6 contains the second assignment to self.x.

Expected Behavior

mypy should be able to determine that the type of C.x is int.

Actual Behavior

The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].

So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.

Your Environment

mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.

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 dem bereitgestellten Python-Reproducer und verfolge die Typinferenz von mypy für die erste Attributzuweisung, wenn der Kontrollfluss diesen Zweig als unerreichbar markiert. Bestätige die Korrektur, indem du mypy erneut für das Beispiel ausführst: C.x sollte ohne Fehler als int inferiert werden, während der Fall Optional[str] weiterhin funktionieren sollte.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

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

Neue Issues direkt in Ihr Postfach

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