python / python/mypy

Overzealous truthy-bool check in finally block

Offen
#16,193 3 Kommentare 4 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen

Dieses Issue hat noch niemand übernommen.

feature
Vorherrschende Sprache
Python
Sterne
20.6k
Forks
3.3k
PR-Merge-Kennzahlen
PR-Kennzahlen ausstehend

Beschreibung

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

Beitragsleitfaden

Beitragsleitfaden öffnen

Erste Schritte

  1. Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
  3. Forke das Repository und arbeite in einem Branch.
  4. Öffne einen Pull Request, der die Issue-Nummer nennt.

Rechercherichtung

Führen Sie das bereitgestellte Beispiel mit mypy 1.5.1 und --enable-error-code=truthy-bool aus und untersuchen Sie anschließend das Narrowing im finally-Block sowie die truthy-bool-Prüfung, die an den gemeldeten Diagnosen beteiligt ist. Die Aufgabe ist abgeschlossen, wenn das Beispiel keinen redundanten Truthiness-Fehler mehr meldet und dabei das korrekte Narrowing und die Diagnosen für andere finally-Fälle erhalten bleiben.

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
Klar beschrieben
Anfängerfreundlichkeit
38/100

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.