python / python/mypy

Flow-sensitive typing ignores dictionary key mutation

Offen
#10,185 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

bug topic-type-narrowing
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

Bug Report

mypy allows runtime type checks for dictionary items. However it ignores subsequent dictionary mutations. This leads to mypy accepting code that fails at runtime.

To Reproduce

from typing import Dict, Optional

foo_dict: Dict[str, Optional[str]] = {'bar': 'baz'}

if foo_dict['bar'] is not None:
    foo_dict['bar'] = None
    foo_dict['bar'].upper()

Expected Behavior

mypy reports .upper() call as error. This is similar to what already happens with object attributes:

from dataclasses import dataclass
from typing import Optional

@dataclass
class Foo:
    bar: Optional[str]

foo = Foo(bar='baz')

if foo.bar is not None:
    foo.bar = None
    foo.bar.upper()

For such code mypy outputs the following error: "None" has no attribute "upper".

Actual Behavior

mypy reports no error.

Your Environment

  • Mypy version used: 0.812
  • Mypy command-line flags: --strict
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.6.8
  • Operating system and version: Windows 8.1

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, die Python-Reproduktion mit mypy --strict auszuführen und sie mit dem dataclass-Attributbeispiel zu vergleichen, wobei du bestätigst, dass der Dictionary-Fall akzeptiert wird, während der Attributfall abgelehnt wird. Verfolge die flusssensitive Narrowing-Logik für Dictionary-Elementausdrücke und füge Abdeckung für die Mutation hinzu; fertig, wenn mypy den .upper()-Aufruf als Fehler meldet.

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
Größtenteils klar
Anfängerfreundlichkeit
45/100

Neue Issues direkt in Ihr Postfach

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