python / python/mypy

Type narrowing fails for union of iterable and dictionary when using `isinstance(x, Iterable)` in a conditional

Aperta
#13,709 0 commenti 4 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

bug topic-type-narrowing
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

When using Union[Iterable[int], Dict[str, int]] together with isinstance(x, Iterable) in a conditional, the narrowing of the type does not work as expected. The previously correctly narrowed type is reverted to the un-narrowed type inside the branch.

To Reproduce

from typing import Dict, Iterable, Union


def test_iterable(x: Union[Iterable[int], Dict[str, int]]) -> Iterable[int]:
    if isinstance(x, dict):
        return [1, 2, 3]
    reveal_type(x)  # typing.Iterable[builtins.int]
    if isinstance(x, Iterable):
        reveal_type(x)  # Union[typing.Iterable[builtins.int], builtins.dict[builtins.str, builtins.int]]
        return x  # mypy falsely returns an error here

Expected Behavior

The type of x should be correctly narrowed down to Iterable[int].

Actual Behavior

Running mypy returns:

example.py:10: error: Incompatible return value type (got "Union[Iterable[int], Dict[str, int]]", expected "Iterable[int]")
Found 1 error in 1 file (checked 1 source file)

The problem persists even if the second if is changed to elif.

Your Environment

I used a clean virtual environment to test, only mypy was installed.

  • Mypy version used: 0.971
  • Python version used: 3.9.5

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 example.py ed esegui mypy su di esso per confermare l’errore segnalato con l’unione e i controlli isinstance. Segui il comportamento del restringimento dei tipi finché il ramo non segnala Iterable[int] come previsto, quindi verifica che l’esempio termini senza l’errore di restituzione incompatibile.

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
Abbastanza chiara
Idoneità per principianti
45/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.