Skip to content

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

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

fromtypingimportOptional# executed with --warn-unreachableclassA:
x: Optional[int]
defexecute(self) ->None:
self.x=Noneforiinrange(3):
ifself.xisNone:
self.x=10else:
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