python / python/mypy

Overzealous truthy-bool check in finally block

Aperta
#16,193 3 commenti 4 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

feature
Lingua principale
Python
Stelle
20.6k
Fork
3.3k
Metriche di merge delle PR
Metriche PR in attesa

Descrizione

Bug Report

If a variable's type is narrowed from potentially-falsey to definitely-truthy during a try block, and that variable is truth-tested during a finally block, the truthy-bool check raises an error even though the variable could in fact be false (if an exception is raised in the try block before the narrowing occurs).

To Reproduce

class A:
    def __init__(self):
        import random
        if random.randint(0, 1):
            raise ValueError
    def close(self): pass

def fn() -> None:
    a: A | None = None
    try:
        a = A()
        print(a)
    finally:
        if a:
            a.close()

fn()

Expected Behavior

Since a might still be None (if A.__init__ raises ValueError) I would expect mypy to not flag the if statement as redundant.

Actual Behavior

$ mypy --enable-error-code=truthy-bool t.py
t.py:14: error: "a" has type "A" which does not implement __bool__ or __len__ so it could always be true in boolean context  [truthy-bool]
Found 1 error in 1 file (checked 1 source file)

If I add a reveal_type(a) line just before if a:, then I get two revealed types:

t.py:14: note: Revealed type is "Union[t.A, None]"
t.py:14: note: Revealed type is "t.A"

which makes me suspect this is an issue where finally statements are desugared into an after-try and an after-except, with different narrowings applied to each one, and truthy-bool is only complaining about one of those.

Your Environment

$ mypy --version
mypy 1.5.1 (compiled: yes)
$ python --version
Python 3.11.5

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

Eseguire l'esempio fornito con mypy 1.5.1 e --enable-error-code=truthy-bool, quindi esaminare il narrowing nel blocco finally e il controllo truthy-bool coinvolto nelle diagnosi segnalate. Il lavoro è completato quando l'esempio non segnala più un errore di truthiness ridondante, preservando al contempo il narrowing corretto e le diagnosi per gli altri casi di finally.

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
Specificata chiaramente
Idoneità per principianti
38/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.