python / python/mypy

Incompatible type "Type[ImportError]"; expected "Type[Exception]"

Aperta
#14,443 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

Mypy appears not to consider ImportError to be an exception type in some cases.

To Reproduce

y = [
    # ValueError,
    ImportError,  # error: List item 0 has incompatible type "Type[ImportError]"; expected "Type[Exception]"  [list-item]
    AttributeError,
]
reveal_type(y)  # note: Revealed type is "builtins.list[def (*args: builtins.object, *, name: Union[builtins.str, None] =, obj: Union[builtins.str, None] =) -> builtins.Exception]"

The ordering of the list elements doesn't seem to impact the behaviour.

If you un-comment the ValueError however:

y = [
    ValueError,
    ImportError,
    AttributeError,
]
reveal_type(y)  # note: Revealed type is "builtins.list[builtins.type]"

While this is perhaps less precise than I'd hope (I'd hope to get list[type[Exception]]) it feels more right to me.

Adding an annotation to the variable (y: list[type[Exception]]) does help mypy see that this is ok, however in my original use-case the list being constructed was passed to a decorator function, so there was no easy opportunity to annotate it.

Your Environment

  • Mypy version used: 0.991
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11

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 Python fornito con mypy 0.991 o con un checkout corrente e confronta i tipi inferiti con e senza ValueError. Traccia l’inferenza degli elementi della lista e la gestione del tipo di eccezione, quindi aggiungi un test di regressione che mostri che ImportError è accettato nella lista e verifica il tipo rivelato atteso.

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

Valutazione

Stack tecnologico
python
Ambito
tooling
Tipo di issue
Bug
Difficoltà
3/5
Tempo stimato
1-2 giorni
Stato di attività
Ferma
Chiarezza
Abbastanza chiara
Idoneità per principianti
38/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.