--possibly-undefined misses for-loop conditional definitions
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
ran into the same issue, just sharing a shorter reproducer
items: list[int] = []
for i in items:
pass
print(i) # will fail in runtime!