Skip to content

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

Closed
@autosquash

Description

@autosquash

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-reachabilityDetecting unreachable codetopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions