2

I have a function as below to get managed resource:


    from contextlib import contextmanager

    @contextmanager
    def getMyClass() -> MyClass:
       ...
       obj = ...
       try:
          yield obj
          ...
       except:
          ...
       finally:
          ...

by specifying Type for the getMyClass function, I suppose this got object can be recognized in with...as statement as below:


   with getMyClass() as obj:
      obj.fun1()

However, VSCode can't recognize the type of obj and the intellisense pop-up menu is not shown. Is it possible to get what I need?

PS: I also check PyCharm, it doesn't show the intellisense pop-up menu either.

jones
  • 317
  • 3
  • 13
  • Is `getMyClass` actually a context manager? Looking at your code, it seems to be a normal function. Trying to use it as a context manager should raise an AttributeError. – shmee Jul 11 '19 at 09:17
  • @shmee I revised the code more clearly. – jones Jul 11 '19 at 10:53
  • 1
    Thank you. Based on my PyCharm testing, the correct return type annotation sould be `-> ContextManager[MyClass]` with `ContextManager` being imported from the `typing` module. I'm hesitant to post this as an answer right now, because I'm convinced, that this is a duplicate of [this question](https://stackoverflow.com/questions/49733699/python-type-hints-and-context-managers). Yet, the answer seems to have never been tried in an actual context with a type other than `None`. I'd like to wait for the other answerer's opinion first. – shmee Jul 11 '19 at 11:04

1 Answers1

0

This technically depends on which IntelliSense provider you're using (Jedi or the language server). In the case of the latter, it has not been implemented yet.

Brett Cannon
  • 14,438
  • 3
  • 45
  • 40