Skip to content

Incompatible types in assignment when a with block has inner method #16423

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jayaseelan-james opened this issue Nov 8, 2023 · 1 comment
Labels
bug mypy got something wrong

Comments

@jayaseelan-james
Copy link

jayaseelan-james commented Nov 8, 2023

Bug Report

mypy reports an Incompatible types in assignment error when the variable name defined is same across "with" blocks and any of the "with" block contain an inner method. I hope this is on the lines of #15605 and a possible variant of #12246.

To Reproduce

Please use the below code:

with open('file1', 'r') as f:
    def do_something(x: int, y: int) -> int:
        return x + y
    
    do_something(2, 3)

with open('file2', 'rb') as f:
    pass

Expected Behavior

Type check passes.

Actual Behavior

I observed the following error:

main.py:7: error: Incompatible types in assignment (expression has type "BufferedReader", variable has type "TextIOWrapper") [assignment]

Your Environment

  • Mypy version used: 1.6.1
  • Mypy command-line flags: None, just ran mypy main.py
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.9.13
@jayaseelan-james jayaseelan-james added the bug mypy got something wrong label Nov 8, 2023
@chriselion
Copy link

A (maybe) simpler repro:

with open("my_file.json") as f:
    pass

with open("my_file.bin", 'rb') as f:
    pass

def noop():
    pass

with output

main.py:4: error: Incompatible types in assignment (expression has type "BufferedReader", variable has type "TextIOWrapper")  [assignment]
Found 1 error in 1 file (checked 1 source file)

(playground)

Interestingly, if you comment out the noop() function, the error goes away.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

2 participants