"Cannot determine type" if first assignment to attribute is unreachable
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
To Reproduce
Run mypy on the following code:
class C:
def __init__(self, a: str) -> None:
if a is None:
self.x = 123
else:
self.x = 456
It will output:
testcase.py:6: error: Cannot determine type of 'x'
Line 6 contains the second assignment to self.x.
Expected Behavior
mypy should be able to determine that the type of C.x is int.
Actual Behavior
The fact that a is annotated as str means that mypy determines that a is None is never true and therefore the first assignment to self.x is unreachable. The problem disappears if a is annotated as Optional[str].
So it looks like mypy half-ignores the first assignment to self.x: it doesn't use the type information available there since the code is unreachable, but it still considers it the assignment that determines the type of self.x.
Your Environment
mypy 0.790 with default configuration, running on Python 3.8.5 on openSUSE Linux.
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
Start with the provided Python reproducer and trace mypy's type inference for the first attribute assignment when control flow marks that branch unreachable. Confirm the fix by rerunning mypy on the example: C.x should be inferred as int without an error, while the Optional[str] case should continue to work.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Bug
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 45/100