mypy cannot detect class attribute change if asserted but modified in external call
Nessuno ha ancora preso questa issue.
- 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. :)

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
- Leggi tutta la issue e poi la guida ai contributi del progetto.
- Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
- Fai un fork del repository e lavora su un branch.
- 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