python / python/mypy

Wrong type hint after unpacking/swapping

Offen
#9,731 3 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug priority-1-normal
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

Unpacking a tuple in the below scenario results in wrong assumed types.

To Reproduce


import typing as t

def spam(val: t.Union[t.Type, None] = None) -> None:

  def eggs(type_: t.Type) -> None:
    pass

  reveal_type(val)
  if isinstance(val, type):
    reveal_type(val)
    val, foo = None, val
    reveal_type(val)
    reveal_type(foo)
    return eggs(foo)

Expected Behavior

After the line val, foo = None, val, I would expect that

  1. val has type None (ok)
  2. foo has type Type[Any]
  3. the call to eggs() passes

Actual Behavior

$ mypy test.py 
test.py:9: note: Revealed type is 'Union[Type[Any], None]'
test.py:11: note: Revealed type is 'Type[Any]'
test.py:13: note: Revealed type is 'None'
test.py:14: note: Revealed type is 'None'
test.py:15: error: Argument 1 to "eggs" has incompatible type "None"; expected "Type[Any]"
Found 1 error in 1 file (checked 1 source file)

This does not match with my expectations 2 and 3.

Your Environment

Python 3.9
Mypy 0.790
MacOS 10.14.6

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

Führe zunächst das gemeldete Python-Beispiel mit mypy aus und vergleiche die erkannten Typen vor und nach val, foo = None, val. Untersuche die Behandlung von Tuple-Unpacking und eingeengten Variablen durch den Type-Checker. Als erledigt gilt die Aufgabe, wenn foo Type[Any] bleibt und der Aufruf von eggs(foo) ohne Fehler durchläuft.

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
Klar beschrieben
Anfängerfreundlichkeit
35/100

Neue Issues direkt in Ihr Postfach

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