Skip to content

False positive unreachable when variable is set and reset inside loop #14987

Description

@adebrecht661

Bug Report

mypy warns about the right side of a condition being unreachable when a variable is reset in an outer loop, then set again inside the inner loop.

To Reproduce

fromtypingimportOptionaltest: Optional[float] =Nonereveal_type(test) # Revealed type: Union[builtins.float, None]foriinrange(10):
test=Nonereveal_type(test) # Revealed type: None (???)forkinrange(10):
iftestisNoneork>test:
test=k

Expected Behavior

No error.

Actual Behavior

mypy outputs error: Right operand of "or" is never evaluated. This is clearly because the type of test is re-evaluated at some point, even though it was declared with a type and no statement narrows that type.

This appears related to #7204, #8721, #8865, #13973, #14120, except it can't be solved by declaring the type of the variable before the loop in which it's updated (because that violates no-redef).

Note: I'm not sure why anyone would want to actually do this in practice. But I thought it might provide a useful test case.

Your Environment

  • Mypy version used: 1.1.1
  • Mypy command-line flags: --disable-error-code name-defined, plus a few others that I don't believe could possibly have any relevance.
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.10.10

Metadata

Metadata

Assignees

Labels

bugmypy got something wrong

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions