How can I annotate the yield type of a contextmanager
in PyCharm so that it properly guesses the type of the value used in the with
clauses - just
This is a current PyCharm issue: PY-36444
A workaround for the issue is to rewrite an example code of:
from contextlib import contextmanager
@contextmanager
def generator_function():
yield "some value"
with generator_function() as value:
print(value.upper()) # no PyCharm autocompletion
to
from contextlib import contextmanager
from typing import ContextManager
def wrapper() -> ContextManager[str]:
@contextmanager
def generator_function():
yield "some value"
return generator_function()
with wrapper() as value:
print(value.upper()) # PyCharm autocompletion works
There is also an easier workaround of annotating the return type with ContextManager[str]
but there are multiple reasons against this: