python / python/mypy

False positive with variable key in Mapping with Optional value

Offen
#10,163 2 Kommentare 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug false-positive
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

When using a mapping with an Optional value type, accessing a value using a variable key instead of a literal key prevents a None check from working properly.

To Reproduce

  1. Put the following code in test.py:
from typing import Mapping, Optional

FOO: str = "foo"

def func(text: str) -> None:
    _ = text

data: Mapping[str, Optional[str]] = {FOO: "bar"}

if data[FOO] is not None:
    func(data[FOO])  # Line 11

if data["foo"] is not None:
    func(data["foo"])
  1. Run mypy test.py

Expected Behavior

mypy should not output any errors. As the above example shows, using a string literal instead of a variable containing a string does not cause any errors, even though the code is otherwise identical. The "Optional types and the None type" section of the documents says "supported checks for guarding against a None value include if x is not None", so this code should work.

Actual Behavior

mypy outputs the following:

test.py:11: error: Argument 1 to "func" has incompatible type "Optional[str]"; expected "str"  [arg-type]

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): show_error_codes = True
  • Python version used: 3.7.9
  • Operating system and version: macOS 10.15.7 (19H524)

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 Reproducer in test.py und führe mypy test.py aus, um zu bestätigen, dass sich der Fall mit variablem Schlüssel und der Fall mit literalem Schlüssel unterscheiden. Verfolge den Pfad der Typprüfung für den Zugriff auf Mapping und die Eingrenzung von Optional und füge anschließend einen Regressionstest hinzu, der den Fall mit variablem Schlüssel abdeckt. Als erledigt gilt die Aufgabe, wenn beide Aufrufe innerhalb der Guards ohne Fehler typgeprüft werden.

Vom Indexierungsmodell aus dem Issue-Text verfasst.

Bewertung

Tech-Stack
python
Bereich
compilers, 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.