False positive for Union[type, ...] and inspect.isclass()
Nessuno ha ancora preso questa issue.
- Lingua principale
- Python
- Stelle
- 20.6k
- Fork
- 3.3k
- Metriche di merge delle PR
- Metriche PR in attesa
Descrizione
Bug Report
When a variable's type is declared as a union that includes type (or typing.Type[...]), mypy does not take into account whether usage of that variable occurs inside of an if inspect.isclass(...) conditional block, leading to false positives.
To Reproduce
Python code
from inspect import isclass
registry: dict[str, type] = {}
def decorator_factory(arg: str | type):
if isclass(arg):
registry[arg.__name__.lower()] = arg
return arg
else:
def decorator(cls: type):
registry[arg] = cls
return cls
return decorator
@decorator_factory
class Foo:
pass
@decorator_factory("alt")
class Bar:
pass
Expected Behavior**
mypy reports no errors
Actual Behavior
main.py:11: error: Invalid index type "str | type" for "dict[str, type]"; expected type "str" [index]
Found 1 error in 1 file (checked 1 source file)
Workaround
Using typing.cast to narrow the union explicitly.
Python code
from inspect import isclass
from typing import cast, TYPE_CHECKING
registry: dict[str, type] = {}
def decorator_factory(arg: str | type):
if isclass(arg):
registry[arg.__name__.lower()] = arg
return arg
else:
if TYPE_CHECKING:
arg = cast(str, arg)
def decorator(cls: type):
registry[arg] = cls
return cls
return decorator
@decorator_factory
class Foo:
pass
@decorator_factory("alt")
class Bar:
pass
Your Environment
- Mypy version used: 1.7.1
- Mypy command-line flags: (mypy-play defaults)
- Mypy configuration options from
mypy.ini(and other config files): (mypy-play defaults) - Python version used: 3.12
Guida per i contributori
Apri la guida per i contributori
Come iniziare
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- Apri una pull request che faccia riferimento al numero della issue.
Direzione di ricerca
Inizia eseguendo il reproducer collegato con mypy e confronta l’errore segnalato con il comportamento previsto relativo a inspect.isclass() e Union[type, ...]. Traccia il percorso del restringimento dei tipi per inspect.isclass, quindi aggiungi la copertura di regressione per il reproducer. Verifica che mypy non segnali errori senza la soluzione alternativa con cast.
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
- 38/100