Skip to content

Incompatible types in assignment (expression has type "BinaryIO", variable has type "TextIO") #10982

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

Closed
jdhao opened this issue Aug 16, 2021 · 3 comments
Labels
bug mypy got something wrong

Comments

@jdhao
Copy link

jdhao commented Aug 16, 2021

Bug Report

mypy reports correct reading of pickle files as error.

To Reproduce

Use the following code:

import json
import pickle

with open('test_ids.json') as f:
    my_ids = json.load(f)

for _id in my_ids:
    id_path = f'{_id}.pkl'

    with open(id_path, 'rb') as f:
        v2_feat = pickle.load(f)

Then use mypy to check the code: mypy test.py

Expected Behavior

No error occurs.

Actual Behavior

I see the following errors:

test.py:10: error: Incompatible types in assignment (expression has type "BinaryIO", variable has type "TextIO")
test.py:11: error: Argument 1 to "load" has incompatible type "TextIO"; expected "IO[bytes]"

Your Environment

  • Mypy version used: 0.910
  • Mypy command-line flags: none
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.7.6
  • Operating system and version: CentOS 7.4
@jdhao jdhao added the bug mypy got something wrong label Aug 16, 2021
@emmatyping
Copy link
Member

mypy is technically correct here. Note that even after a context manager scope has been left, the variable f is still valid.

with open('test.txt') as f:
    pass
print(f) # works

Therefore, you are actually re-defining the variable f between uses of the context manager.

I do understand this is rather un-intuitive but I'm not sure if there is a good workaround for this pattern.

@erictraut
Copy link

I would expect this to work if you specify the --allow-redefinition flag, but it still generates an error.

@emmatyping emmatyping reopened this Aug 16, 2021
@AlexWaygood
Copy link
Member

Mypy no longer emits an error for this code (I believe this is a result of #12254).

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

4 participants