Skip to content

False positive with --warn-unreachable when an instance variable is modified inside a for loop #13973

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

Closed
autosquash opened this issue Oct 31, 2022 · 0 comments · Fixed by #18433
Labels
bug mypy got something wrong topic-reachability Detecting unreachable code topic-type-narrowing Conditional type narrowing / binder

Comments

@autosquash
Copy link

Bug Report

mypy mark as unreachable code that is perfectly reachable, perhaps because it interprets an instance variable typed as Optional to always be None.

To Reproduce

from typing import Optional

# executed with --warn-unreachable

class A:
    x: Optional[int]

    def execute(self) -> None:
        self.x = None
        for i in range(3):
            if self.x is None:
                self.x = 10
            else:
                self.x = 20  # error: Statement is unreachable  [unreachable]
            print(self.x)


a = A()
a.execute()

Gist
Playground URL

Expected Behavior

No errors.

Actual Behavior

Showing: error: Statement is unreachable [unreachable]

Your Environment

  • Mypy version used: 0.982
  • Mypy command-line flags: --warn-unreachable
  • Mypy configuration options from mypy.ini (and other config files):
  • Python version used: 3.10
@autosquash autosquash added the bug mypy got something wrong label Oct 31, 2022
@JelleZijlstra JelleZijlstra added topic-type-narrowing Conditional type narrowing / binder topic-reachability Detecting unreachable code labels Oct 31, 2022
tyralla added a commit to tyralla/mypy that referenced this issue Jan 9, 2025
Fixes python#18348
Fixes python#13973
Fixes python#11612
Fixes python#8721
Fixes python#8865
Fixes python#7204

I manually checked all the listed issues.  Some of them were already partly fixed by python#18180.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong topic-reachability Detecting unreachable code topic-type-narrowing Conditional type narrowing / binder
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants