python / python/mypy

False positive in conditional with with statements

Open
#15,605 1 comment 2 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

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

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 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.