Skip to content

[used-before-def] fix false positive inside loop #14307

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

Merged
merged 1 commit into from
Dec 19, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion mypy/partially_defined.py
Original file line number Diff line number Diff line change
Expand Up @@ -322,7 +322,10 @@ def process_definition(self, name: str) -> None:
# Was this name previously used? If yes, it's a used-before-definition error.
refs = self.tracker.pop_undefined_ref(name)
for ref in refs:
self.var_used_before_def(name, ref)
if self.loops:
self.variable_may_be_undefined(name, ref)
else:
self.var_used_before_def(name, ref)
self.tracker.record_definition(name)

def visit_global_decl(self, o: GlobalDecl) -> None:
Expand Down
7 changes: 6 additions & 1 deletion test-data/unit/check-possibly-undefined.test
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ def f2() -> None:
x = 2
w = x # No error.

[case testDefinedDifferentBranchPossiblyUndefined]
[case testPossiblyUndefinedLoop]
# flags: --enable-error-code possibly-undefined --enable-error-code used-before-def

def f0() -> None:
Expand Down Expand Up @@ -423,6 +423,11 @@ def f3() -> None:
else:
y = x # E: Name "x" may be undefined

def f4() -> None:
while int():
y = x # E: Name "x" may be undefined
x: int = 1

[case testAssert]
# flags: --enable-error-code possibly-undefined
def f1() -> int:
Expand Down