MyPy incorrectly tracks attribute type in chained ifs with assignment
Open
Nobody has claimed this yet.
bug
false-positive
priority-1-normal
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
$ cat b.py
from typing import Optional
class A:
x: Optional[str]
def f(a: A) -> None:
if not a.x:
pass
elif a.x == "x":
a = A()
else:
y: str = a.x
$ mypy b.py
b.py:12: error: Incompatible types in assignment (expression has type "Optional[str]", variable has type "str")
$ mypy --version
mypy 0.701
The assignment a = A() should not affect the code in the else branch.
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce the diagnostic with b.py using mypy 0.701, then trace type narrowing through the chained if/elif/else and the reassignment of a. Done means the final assignment to y is accepted with a.x treated as str, without changing the reported behavior of other branches.
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
- 42/100