mypy icon indicating copy to clipboard operation
mypy copied to clipboard

--possibly-undefined misses for-loop conditional definitions

Open AndrewFerr opened this issue 2 years ago • 1 comments

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

AndrewFerr avatar Sep 05 '23 14:09 AndrewFerr

ran into the same issue, just sharing a shorter reproducer

items: list[int] = []
for i in items:
    pass
print(i)  # will fail in runtime!

karlicoss avatar Aug 27 '24 19:08 karlicoss