如何在 PyCharm 中正确注释 ContextManager? [英] How to properly annotate a ContextManager in PyCharm?
问题描述
如何在 PyCharm 中注释 contextmanager
的产量类型,以便它正确猜测 with
子句中使用的值的类型 - 就像它猜测的那样在 with open(...) as f
中创建的 f
是一个文件吗?
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 as it guesses that the f
created in with open(...) as f
is a file?
例如,我有一个这样的上下文管理器:
For example, I have a context manager like this:
@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
上的方法)?当然,我可以在每个 with
语句之后添加类似 # type: Path
的注释,但似乎可以通过正确注释 temp_border_file
来完成>.
How do I let PyCharm know that every borders_f
created like this is a pathlib.Path
(and thus enable the autocompletion for the Path
methods on border_f
)? Of course, I can make a comment like # type: Path
after every with
statement, but it seems that this can be done by properly annotating temp_border_file
.
我尝试了 Path
、typing.Iterator[Path]
和 typing.Generator[Path, None, None]
作为返回类型temp_border_file
,以及在上下文管理器的代码中的 borders_file
上添加 # type: Path
,但似乎没有帮助.
I tried Path
, typing.Iterator[Path]
and typing.Generator[Path, None, None]
as the return type of temp_border_file
, as well as adding # type: Path
on borders_file
within the context manager's code, but it seems like it doesn't help.
推荐答案
我相信您可以使用 typing
中的 ContextManager
,例如:
I believe you can use ContextManager
from typing
, e.g.:
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
这篇关于如何在 PyCharm 中正确注释 ContextManager?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!