Dict's .get() method doesn't limit possible types of the given element
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
from typing import Optional, Dict
def test(arg: str) -> None:
...
def this_fails(arg: Dict[str, Optional[str]]) -> None:
if arg.get("key") is not None:
test(arg["key"]) # error
def this_fails_also(arg: Dict[str, Optional[str]]) -> None:
if arg.get("key") is not None:
test(arg.get("key")) # error
def but_this_pass(arg: Dict[str, Optional[str]]) -> None:
if arg.get("key") and arg["key"] is not None:
test(arg["key"])
def this_pass_also_but_is_unsafe(arg: Dict[str, Optional[str]]) -> None:
if arg["key"] is not None:
test(arg["key"])
First two methods fail due to Argument 1 to "test" has incompatible type "Optional[str]"; expected "str" error.
Mypy seems to see no relation between arg["key"] and arg.get("key") and it should (IMHO).
I'm not sure if this is a bug and not a feature request, but arg.get("key") and arg["key"] is not None looks redundant for me.
Expected Behavior
The possibility of arg["key"] is None should be excluded by if arg.get("key") is not None because the inner block is unreachable if "key in arg and arg["key"] is None so the value is no longer Optional.
Environment
mypy 0.942
Python 3.10.0
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Reproduziere die beiden fehlschlagenden Beispiele und die erfolgreichen Vergleiche aus dem Issue mit mypy 0.942 und Python 3.10. Untersuche, wie sich die Typverengung auf die Beziehung zwischen von Dict.get() zurückgegebenen Werten und indizierten Zugriffen auswirkt, und betrachte die Arbeit als abgeschlossen, wenn das gemeldete sichere Muster den Wert auf str verengt, ohne den unsicheren Fall zu akzeptieren.
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
- 40/100