--possibly-undefined misses for-loop conditional definitions
Dieses Issue hat noch niemand übernommen.
- Vorherrschende Sprache
- Python
- Sterne
- 20.6k
- Forks
- 3.3k
- PR-Merge-Kennzahlen
- PR-Kennzahlen ausstehend
Beschreibung
Bug Report
--enable-error-code possibly-undefined does not detect when a local variable is conditionally set by a for loop.
To Reproduce
https://gist.github.com/mypy-play/25a51361be6d697e25b32587e4cba351
https://mypy-play.net/?mypy=latest&python=3.11&gist=25a51361be6d697e25b32587e4cba351
Expected Behavior
If a variable is set by a for loop over an iterable (i.e. for x in l), and
- that variable was not previously initialized
- the iterable may be empty
then mypy should warn against a UnboundLocalError that would be raised by accessing that variable after the loop, were that iterable to be empty.
Actual Behavior
mypy reports no issues.
A workaround is to wrap the for loop with an if condition to check if the iterable being looped over is not empty.
For example:
if l:
for x in l:
# ...
Your Environment
- Mypy version used: 1.5.1
- Mypy command-line flags:
--enable-error-code possibly-undefined - Mypy configuration options from
mypy.ini(and other config files): none - Python version used: 3.11.4
Beitragsleitfaden
Erste Schritte
- Lies das ganze Issue und danach den Beitragsleitfaden des Projekts.
- Schreib ins Issue, dass du es übernimmst — das erspart doppelte Arbeit.
- Forke das Repository und arbeite in einem Branch.
- Öffne einen Pull Request, der die Issue-Nummer nennt.
Rechercherichtung
Beginne mit der verlinkten mypy-play-Reproduktion und dem Flag --enable-error-code possibly-undefined, um zu bestätigen, dass für ein leeres Iterable die Warnung fehlt. Verfolge die relevante for-loop-Flussanalyse, füge einen Regressionstest für den Fall einer bedingten Definition hinzu und überprüfe, dass mypy den erwarteten possibly-undefined-Fehler meldet.
Vom Indexierungsmodell aus dem Issue-Text verfasst.
Bewertung
- Tech-Stack
- python
- Bereich
- compilers, devtools
- Issue-Typ
- Bug
- Schwierigkeit
- 4/5
- Geschätzter Aufwand
- 3-5 Tage
- Aktivitätsstatus
- Veraltet
- Klarheit
- Größtenteils klar
- Anfängerfreundlichkeit
- 45/100