首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何正确注释ContextManager中的PyCharm?

如何正确注释ContextManager中的PyCharm?
EN

Stack Overflow用户
提问于 2018-03-17 11:06:29
回答 2查看 3.9K关注 0票数 13

我如何在contextmanager中注释PyCharm的屈服类型,以便正确地猜测with子句中使用的值的类型--就像它猜测在with open(...) as f中创建的f是一个文件一样?

例如,我有这样一个上下文管理器:

代码语言:javascript
复制
@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来实现。

我尝试了Pathtyping.Iterator[Path]typing.Generator[Path, None, None]作为temp_border_file的返回类型,并在上下文管理器的代码中添加了borders_file上的# type: Path,但这似乎没有帮助。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-03-17 12:04:33

下面是肮脏的解决办法。会破坏mypy。最好不要用它。

我相信您可以使用来自typingtyping,例如:

代码语言:javascript
复制
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
票数 17
EN

Stack Overflow用户

发布于 2019-06-15 14:52:29

这是当前的PyCharm问题:皮-36444

解决此问题的方法是重写以下示例代码:

代码语言:javascript
复制
from contextlib import contextmanager

@contextmanager
def generator_function():
    yield "some value"

with generator_function() as value:
    print(value.upper())  # no PyCharm autocompletion

代码语言:javascript
复制
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]注释返回类型还有一个更简单的解决办法,但有多种原因反对这样做:

  • mypy将正确地发出此注释的错误,如PyCharm问题中详细描述的那样。
  • 这不一定在将来起作用,因为PyCharm有希望解决这个问题,从而破坏这个解决办法。
票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49335263

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档