python / python/mypy

mypy cannot detect class attribute change if asserted but modified in external call

Open
#13,240 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
20.6k
Forks
3.3k
PR merge metrics
PR metrics pending

Description

Bug Report

mypy cannot detect class attribute change if assert but modified in external call
This is a case found when I'm trying to check the close status first, and after some logic, close it then.

The print(1) in f1() is reachable, but mypy think Statement is unreachable because we asserted assert not self._closed first, however, it was changed in the close() call
For the f2() we modify the self._close inplace, so mypy is happy with it.

I think it may be hard and not worth to fix, just reported to let you know. :)

image

To Reproduce

save the code and then run mypy --warn-unreachable assert_but_change.py

# assert_but_change.py
class Foo:
    def __init__(self) -> None:
        self._closed = False

    def f1(self) -> None:
        assert not self._closed

        # do some logic
        self.close()

        if self._closed:
            print(1)

    def close(self) -> None:
        self._closed = True

    def f2(self) -> None:
        assert not self._closed
        self._closed = True

        if self._closed:
            print(1)

Expected Behavior

the print(1) in f1() is reachable, mypy should not complain
just like the print(1) in f2()

Actual Behavior

Statement is unreachable

Your Environment

  • Mypy version used: mypy 0.971
  • Mypy command-line flags: --warn-unreachable
  • Mypy configuration options from mypy.ini (and other config files): No
  • Python version used: cpython 3.9.4
  • Operating system and version: windows 10

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

Start with the supplied assert_but_change.py reproduction and run mypy --warn-unreachable against it. Trace how the assertion, the external close() call, and the later self._closed check are analyzed, then verify that f1() no longer reports the reachable print(1) as unreachable while f2() remains valid.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.