python / python/mypy

mypy cannot detect class attribute change if asserted but modified in external call

Aperta
#13,240 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

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

Descrizione

Bug Report

mypy cannot detect class attribute change if assert but modified in external call
This is a case found when I'm trying to check the close status first, and after some logic, close it then.

The print(1) in f1() is reachable, but mypy think Statement is unreachable because we asserted assert not self._closed first, however, it was changed in the close() call
For the f2() we modify the self._close inplace, so mypy is happy with it.

I think it may be hard and not worth to fix, just reported to let you know. :)

image

To Reproduce

save the code and then run mypy --warn-unreachable assert_but_change.py

# assert_but_change.py
class Foo:
    def __init__(self) -> None:
        self._closed = False

    def f1(self) -> None:
        assert not self._closed

        # do some logic
        self.close()

        if self._closed:
            print(1)

    def close(self) -> None:
        self._closed = True

    def f2(self) -> None:
        assert not self._closed
        self._closed = True

        if self._closed:
            print(1)

Expected Behavior

the print(1) in f1() is reachable, mypy should not complain
just like the print(1) in f2()

Actual Behavior

Statement is unreachable

Your Environment

  • Mypy version used: mypy 0.971
  • Mypy command-line flags: --warn-unreachable
  • Mypy configuration options from mypy.ini (and other config files): No
  • Python version used: cpython 3.9.4
  • Operating system and version: windows 10

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 la riproduzione fornita in assert_but_change.py ed esegui mypy --warn-unreachable su di essa. Traccia come vengono analizzati l’assertion, la chiamata esterna a close() e il successivo controllo di self._closed, quindi verifica che f1() non segnali più print(1), che è raggiungibile, come irraggiungibile, mentre f2() rimane valido.

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
35/100

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.