False positive in conditional with with statements
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
Opening files with the same variable name in with statements in if statements fails type checks if the type of the result of the with statement is different. In this example, the difference is opening a file with 'rb' vs 'r'. Looks like this might be a variation of https://github.com/python/mypy/issues/12246.
To Reproduce
from pathlib import Path
def check_something() -> bool:
return False
path = Path("foo")
if check_something():
with path.open("rb") as f:
pass
else:
with path.open("r") as f:
pass
Expected Behavior
Type check passes.
Actual Behavior
test.py:16: error: Incompatible types in assignment (expression has type "TextIOWrapper", variable has type "BufferedReader") [assignment]
Environment
- Mypy version used: 1.4.1
- Mypy command-line flags: None, I ran
mypy test.py - Mypy configuration options from
mypy.ini(and other config files): None - Python version used: 3.11.4
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 by reproducing the example in test.py with Python 3.11.4 and mypy 1.4.1 using mypy test.py. Investigate how the two conditional with statements handle the shared variable f; done means the example type-checks without the incompatible-assignment error.
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
- Clearly specified
- Newbie friendliness
- 45/100