如何contextmanager在 PyCharm 中注释 a 的 yield 类型,以便它正确猜测with子句中使用的值的类型 - 就像它猜测fcreated inwith open(...) as 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(从而启用Path方法的自动完成border_f)?当然,我可以# type: Path在每条with语句之后发表评论,但似乎可以通过正确注释来完成temp_border_file。
我尝试了Path,typing.Iterator[Path]并typing.Generator[Path, None, None]作为 , 的返回类型temp_border_file,以及在上下文管理器的代码中添加# type: Path,borders_file但似乎没有帮助。