我如何在contextmanager中注释PyCharm的屈服类型,以便正确地猜测with子句中使用的值的类型--就像它猜测在with open(...) as f中创建的f是一个文件一样?
例如,我有这样一个上下文管理器:
@contextlib.contextmanager
def temp_borders_file(geometry: GEOSGeometry, name='borders.json'):
with TemporaryDirectory() as temp_dir:
borders_file = Path(dir) / name
with borders_file.open('w+') as f:
f.write(geometry.json)
yield borders_file
with temp_borders_file(my_geom) as borders_f:
do_some_code_with(borders_f...)我如何让PyCharm知道像这样创建的每个borders_f都是一个pathlib.Path (从而为border_f上的Path方法启用了自动完成)?当然,我可以在每个# type: Path语句之后做出类似于with的评论,但是这似乎可以通过正确地注释temp_border_file来实现。
我尝试了Path、typing.Iterator[Path]和typing.Generator[Path, None, None]作为temp_border_file的返回类型,并在上下文管理器的代码中添加了borders_file上的# type: Path,但这似乎没有帮助。
发布于 2018-03-17 12:04:33
下面是肮脏的解决办法。会破坏mypy。最好不要用它。
我相信您可以使用来自typing的typing,例如:
import contextlib
from typing import ContextManager
from pathlib import Path
@contextlib.contextmanager
def temp_borders_file() -> ContextManager[Path]:
pass
with temp_borders_file() as borders_f:
borders_f # has type Path here发布于 2019-06-15 14:52:29
这是当前的PyCharm问题:皮-36444
解决此问题的方法是重写以下示例代码:
from contextlib import contextmanager
@contextmanager
def generator_function():
yield "some value"
with generator_function() as value:
print(value.upper()) # no PyCharm autocompletion至
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用ContextManager[str]注释返回类型还有一个更简单的解决办法,但有多种原因反对这样做:
https://stackoverflow.com/questions/49335263
复制相似问题