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

Conditional expression in "with" statement inferred as 'object', lacking __enter__ and __exit__ #5512

Open
chkno opened this Issue Aug 20, 2018 · 1 comment

Comments

Projects
None yet
2 participants
@chkno

chkno commented Aug 20, 2018

from tempfile import TemporaryDirectory, TemporaryFile
import sys

use_file = 'directory' not in sys.argv

with (TemporaryFile() if use_file else TemporaryDirectory()) as thing:
    print(thing)

Mypy infers the type of the conditional expression as object rather than Union[IO,TemporaryDirectory]

$ mypy multi_with.py

multi_with.py:6: error: "object" has no attribute "__enter__"
multi_with.py:6: error: "object" has no attribute "__exit__"

Explicitly typing the result of the conditional expression makes the error messages go away:

named_intermediate: Union[IO, TemporaryDirectory] = (TemporaryFile() if use_file else TemporaryDirectory())

with named_intermediate as thing:
    print(thing)

I observe this in both mypy versions I tried: 0.600 and 0.620

These past issues and pull requests look relevant:
#3487 Type of conditional expression is join instead of union
#5041 Fix type of conditional statement to Union and not Join.
#5095 Don't always infer unions for conditional expressions

@ilevkivskyi

This comment has been minimized.

Show comment
Hide comment
@ilevkivskyi

ilevkivskyi Aug 23, 2018

Collaborator

Yes, one option is to infer a union for conditional expression. Another option however is to still use join, but fix #3830 (at leat for the situation where we have a protocol context, like ContextManager in this case, which should be pretty straightforward)

Collaborator

ilevkivskyi commented Aug 23, 2018

Yes, one option is to infer a union for conditional expression. Another option however is to still use join, but fix #3830 (at leat for the situation where we have a protocol context, like ContextManager in this case, which should be pretty straightforward)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment