python / python/mypy

Inference in the `else` block of a try-except-else

Aperta
#14,527 2 commenti 2 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

In the else branch of a try-except-else, mypy ought to be able to infer that no except branch was taken.

To Reproduce

https://mypy-play.net/?mypy=latest&python=3.11&gist=306f5b87e1b2eadc3f7692718a21f6b5

import random


def maybe_int() -> int:
    if random.choice([True, False]):
        return 42
    else:
        raise ValueError


def main() -> None:
    try:
        x = maybe_int()
    except ValueError:
        x = None
    else:
        x += 1  # mypy error occurs here

Expected Behavior

At the last line of the example, I expected mypy to infer that the except branch hadn't been taken, and therefore x was of type int, just as it is at the end of the try branch.

Actual Behavior

test.py:17: error: Unsupported operand types for + ("None" and "int")  [operator]
test.py:17: note: Left operand is of type "Optional[int]"

Your Environment

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

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 con il reproducer mypy-play collegato e conferma l’errore Optional[int] nell’esempio try-except-else. Traccia il modo in cui mypy gestisce i rami try, except ed else, quindi aggiungi una copertura di regressione che mostri che x viene inferito come int nel ramo else e che l’errore segnalato viene rimosso.

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

Valutazione

Stack tecnologico
python
Ambito
compilers
Tipo di issue
Bug
Difficoltà
4/5
Tempo stimato
3-5 giorni
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.