Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from

Conversation

ambv
Copy link
Contributor

@ambv ambv commented Aug 20, 2025

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 and others added 3 commits August 20, 2025 17:03
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 python#14209
Fixes python#19690
Copy link
Contributor

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

@cdce8p cdce8p added the topic-possibly-undefined possibly-undefined error code label Aug 21, 2025
@ambv ambv requested a review from ilevkivskyi August 23, 2025 10:34
@ambv
Copy link
Contributor Author

ambv commented Aug 23, 2025

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
topic-possibly-undefined possibly-undefined error code
Projects
None yet
Development

Successfully merging this pull request may close these issues.

try: except: continue inside for: else: causes spurious used-before-def (🐞) for/else with break statement incorrect possibly-undefined error
2 participants