python / python/mypy

False positive with variable key in Mapping with Optional value

Aperta
#10,163 2 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug false-positive
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

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)

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

Inizia con il reproducer in test.py ed esegui mypy test.py per confermare che il caso con chiave variabile e quello con chiave letterale differiscano. Segui il percorso del type checking per l’accesso a Mapping e il narrowing di Optional, quindi aggiungi un test di regressione che copra il caso con chiave variabile. Il lavoro è completato quando entrambe le chiamate protette superano il type checking senza errori.

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

Valutazione

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

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.