python / python/mypy

Dict's .get() method doesn't limit possible types of the given element

Aperta
#12,457 4 commenti 1 reazione 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature priority-2-low topic-type-narrowing
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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

Guida per i contributori

Apri la guida per i contributori

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Direzione di ricerca

Riproduci i due esempi che falliscono e i confronti riusciti dell’issue usando mypy 0.942 e Python 3.10. Analizza in che modo il restringimento del tipo mette in relazione i valori restituiti da Dict.get() con gli accessi indicizzati e considera completato il lavoro quando il pattern sicuro segnalato restringe il valore a str senza accettare il caso non sicuro.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Valutazione

Stack tecnologico
python
Ambito
devtools
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
Stato di attività
Ferma
Chiarezza
Specificata chiaramente
Idoneità per principianti
40/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.