The Wayback Machine - https://web.archive.org/web/20201109034752/https://github.com/microsoft/python-language-server/issues/340
Skip to content
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

with-as should defer type to __enter__ #340

Open
jakebailey opened this issue Nov 2, 2018 · 5 comments
Open

with-as should defer type to __enter__ #340

jakebailey opened this issue Nov 2, 2018 · 5 comments

Comments

@jakebailey
Copy link
Member

@jakebailey jakebailey commented Nov 2, 2018

Take this example:

@contextlib.contextmanager
def noop(x):
    yield x

with noop("foobar") as s:
    print(type(s))  # prints <class 'str'>

The type of s is str, because noop yields x, which is str.

Another example (this one will raise AttributeError, but that's not important):

with contextlib.closing("foobar") as s:
    print(type(s))  # also prints <class 'str'>

In both examples, we say that s is of type ContextManager, which isn't the case. It would be better to determine the type of what comes after as via checking the context manager's __enter__ function return type: https://docs.python.org/3/reference/datamodel.html#object.__enter__

@brettcannon
Copy link
Member

@brettcannon brettcannon commented Jul 11, 2019

Is this blocking any with ... as ... block working?

with open('file.txt') as file:
    file.
@jakebailey
Copy link
Member Author

@jakebailey jakebailey commented Jul 11, 2019

Not from what I can tell:

image

But my original example with the contextmanager decorator doesn't work (probably because we don't handle how the decorator operates for some reason).

@jakebailey
Copy link
Member Author

@jakebailey jakebailey commented Jul 11, 2019

Okay, maybe open isn't the best example, because we could be "cheating" and copy from the left to the right without looking at __enter__, which would work for anything open returns, but the code should have been written and working: https://github.com/microsoft/python-language-server/blob/master/src/Analysis/Ast/Impl/Analyzer/Handlers/WithHandler.cs

@brettcannon
Copy link
Member

@brettcannon brettcannon commented Jul 11, 2019

Ah, stops working with this full snippet:

import contextlib
import typing

@contextlib.contextmanager
def cxt_manager() -> typing.Generator[str, None, None]:
    yield "hello"


# with cxt_manager() as ob:
#     ob

with open('a') as file:
    file.
@MikhailArkhipov
Copy link
Member

@MikhailArkhipov MikhailArkhipov commented Jul 11, 2019

B/c we don't specialize Generator in typing. Typing specializations are not complete, #535.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
3 participants
You can’t perform that action at this time.