Skip to content

False positive in conditional with with statements #15605

Open
@freewilll

Description

@freewilll

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions