python / python/mypy

`generics`: isinstance reports false positives and false negatives

Aperta
#15,438 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

When using a function with a tuple with A Generic as content, mypy fails to deduce the type of the tuple correctly, when correctly narrowed with isinstance (or type). But it says, that wrong code is correct, see the example below for that.

To Reproduce

make a function, that takes a tuple[T] and returns something with T, where T is a TypeVar
Then use isinstance (or even a match case statement for the matter) and narrow the type T, to then return the correct type.

See the following (not so small) example:

import random
from typing import TypeVar, Union

T1 = TypeVar("T1", bound=Union[int, float])
def random_from_range(range: tuple[T1, T1]) -> T1:
    if isinstance(range[0], int) and isinstance(range[1], int):
        min, max = range
        reveal_type(range)
        return 1 #random.randint(min, max)
    elif isinstance(range[0], float) and isinstance(range[1], float):
        min, max = range
        reveal_type(range)
        return 1.0 #random.uniform(min, max)
    else:
        raise RuntimeError(
            "No random range implemented for type {0}, values: {1}".format(
                type(range[0]), range
            )
        )

T2 = TypeVar("T2", bound=Union[int, float])
def random_from_range_wrong(range: tuple[T2, T2]) -> T2:
    if isinstance(range, (int, int)):
        min, max = range
        reveal_type(range)
        return 1 # random.randint(min, max)
    elif isinstance(range, (float, float)):
        min, max = range
        reveal_type(range)
        return 1.0 #random.uniform(min, max)
    else:
        raise RuntimeError(
            "No random range implemented for type {0}, values: {1}".format(
                type(range[0]), range
            )
        )


if __name__ == "__main__":
    try:
        random_from_range((1,0))
        random_from_range((1.0, 2.0))
        print("'random_from_range' should work")
    except Exception:
        print("ERROR: 'random_from_range' should work")
    
    try:
        random_from_range_wrong((1, 0))
        random_from_range_wrong((1.0, 2.0))
        print("ERROR: 'random_from_range' shouldn't work, mypy should see the issue!")
    except Exception:
        print("It didn't work, as expected, but not as reported by mypy")

Expected Behavior

1: random_from_range:

If you check e.g. a tuple[T1, T1] with isinstance(range[0], int) it should narrow the type, at least if you check every tuple element for a tuple, its should narrow the whole tuple. when narrowing a Generic type, all Generics should be narrowed, e.g not both should be required to check

2: random_from_range_wrong:

mypy should report, that the types for range never can be int, or float and interpret the second argument as type OR tuple of types, a tuple there shouldn't be interpreted as type, but as list of types!

Actual Behavior

1:

If you check e.g. a tuple[T1, T1] with isinstance(range[0], int) it doesn't narrow the type, the revealed type is:
tuple[T1, T1] and not tuple[int, T1] or even tuple[int, int]

2:

It interprets the type as tuple[int, int] or tuple[float, float] and then narrows T2 to int or float, the whole functions is correct, but it results in an runtime error (after commenting out reveal_type calls) , since none of the instances map, since the tuple is NEVER of type int or int, which (int, int) checks, it doesn't check for type tuple[int,int]

  • Mypy version used: 1.3.0
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.6

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 eseguendo l’esempio fornito con mypy 1.3.0 e confronta i risultati di reveal_type per random_from_range e random_from_range_wrong. Analizza come i controlli isinstance restringono tuple[T1, T1] e interpreta (int, int), quindi aggiungi una copertura mirata per il comportamento atteso di restringimento e rifiuto. Il lavoro è completato quando le diagnostiche e i tipi rivelati corrispondono alle aspettative indicate.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
5/5
Tempo stimato
Più di una settimana
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.