Incorrect type narrowing for `x in y` pattern when `x` is `type[T]` and `y` is an iterable of class objects
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
As the title suggests, if one uses the type_var in (type1, type2, ...) construct instead of issubtype(type_var, (type1, type2, ...), and type_var is generic, mypy struggles with narrowing down the type.
The same bug happens in pyright.
To Reproduce
from typing import TypeVar
T = TypeVar('T')
def func(typ: type[T], input: str) -> T:
if typ in (str, int, float):
return typ(input) # error: Too many arguments for "object" [call-arg]
else:
raise ValueError() # Just for the sake of demonstration
def func(typ: type[T], input: str) -> T:
if issubclass(typ, (str, int, float)):
return typ(input) # No problem!
else:
raise ValueError() # Just for the sake of demonstration
Expected Behavior
Both versions of the type check act the same.
Actual Behavior
Mypy incorrectly throws Too many arguments for "object" [call-arg] error.
Your Environment
- Mypy version used: 1.11.2
- Mypy command-line flags: N/A
- Mypy configuration options from
mypy.ini(and other config files): N/A - Python version used: 3.12 / 3.10
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
Beginne damit, den bereitgestellten Reproducer mit mypy auszuführen und die Fälle in und issubclass zu vergleichen. Verfolge den Pfad der Typverengung für Membership-Prüfungen und füge einen Regressionstest hinzu, der type[T] mit einem Iterable von Klassenobjekten abdeckt; fertig ist die Änderung, wenn der Aufruf typ(input) im in-Fall akzeptiert wird, ohne das bestehende Verhalten abzuschwächen.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 38/100