mypy icon indicating copy to clipboard operation
mypy copied to clipboard

Fix spurious possibly-undefined errors in for-else with break

Open ambv opened this issue 4 months ago • 4 comments

When a for loop contains branches with break and an else block, variables declared inside those branches were incorrectly discarded from further analysis, leading Mypy to incorrectly report a variable as undefined after the loop or as used before declaration.

With this fix, when a for loop's else block is considered, variables declared in every branch of the for loop body that called break are now considered as defined within the body of the loop.

Fixes #14209 Fixes #19690

ambv avatar Aug 20 '25 15:08 ambv

According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅

github-actions[bot] avatar Aug 20 '25 15:08 github-actions[bot]

@ilevkivskyi, I asked you for review since you reviewed the original change three years back.

ambv avatar Aug 23 '25 10:08 ambv

It would be cool to get this landed, I just stumbled across a similar false positive in our codebase. Is there anything left to be done apart from actually merging this fix?

spt29 avatar Dec 05 '25 10:12 spt29

Is there anything left to be done apart from actually merging this fix?

Yes: https://github.com/python/mypy/pull/19696/files#r2300505910

johnslavik avatar Dec 06 '25 17:12 johnslavik