python / python/mypy

warn-unreachable false-positive when method updates attribute after assert

Open
#11,969 12 comments 11 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug topic-reachability topic-type-narrowing
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Consider the following code:

from dataclasses import dataclass


@dataclass
class Foo:
    value: int
    modified: bool = False

    def update(self) -> None:
        self.value += 1
        self.modified = True


foo = Foo(42)
assert not foo.modified
foo.update()
assert foo.modified
print("Reached")

When this is run, the print("Reached") line is reached, but mypy doesn't seem to realize that. Running mypy --warn-unreachable --pretty on the above code gives:

unreachable03.py:18: error: Statement is unreachable
    print("Reached")
    ^
Found 1 error in 1 file (checked 1 source file)

Your Environment

  • Mypy version used: both v0.931 and the GitHub version as of commit 48d810d5ed25f898d4f220a7476b6b267c289b9a
  • Mypy command-line flags: --warn-unreachable --pretty
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.9.9
  • Operating system and version: macOS 11.6

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the report with the supplied dataclass example using mypy --warn-unreachable --pretty, then trace the unreachable-code analysis around the two assertions and foo.update(). Add a regression test for this example and verify that print("Reached") is no longer reported as unreachable.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.