`generics`: isinstance reports false positives and false negatives
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
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
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
Führe zunächst das bereitgestellte Beispiel mit mypy 1.3.0 aus und vergleiche die reveal_type-Ergebnisse für random_from_range und random_from_range_wrong. Verfolge, wie isinstance-Prüfungen tuple[T1, T1] eingrenzen, und interpretiere (int, int). Füge anschließend eine gezielte Abdeckung für das erwartete Eingrenzungs- und Ablehnungsverhalten hinzu. Als erledigt gilt die Aufgabe, wenn die Diagnosen und aufgedeckten Typen den angegebenen Erwartungen entsprechen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers
- Issue-Typ
- Bug
- Schwierigkeit
- 5/5
- Geschätzter Aufwand
- Über eine Woche
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 35/100