返回方法的 pytests 固定装置的类型提示

fin*_*mer 7 python pytest pycharm python-3.x

我的一些 pytest 固定装置返回一个方法。我想对我的所有方法使用类型提示。说一个方法返回一个我可以Callable在这里使用的方法。这里的问题是:我失去了 IDE PyCharm 中参数的自动完成功能。

没有给出夹具返回值的类型提示:

@pytest.fixture
def create_project():
    def create(location: Path, force: bool = True) -> bool:
        # ...

    return create


def test_project(create_project):
    project_created = create_project()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

使用给定的类型提示:

@pytest.fixture
def create_project() -> Callable[[Path, bool], bool]:
    def create(location: Path, force: bool = True) -> bool:
        # ...

    return create


def test_project(create_project):
    project_created = create_project()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

另一个问题Callable是,我必须在夹具中以及在我使用该夹具的每个测试中描述一次参数和返回类型。

那么有没有更有效的方法呢?

fin*_*mer 10

预期的方式似乎是使用Protocol

from typing import Protocol


class ProjectMaker(Protocol):
    def __call__(self, location: Path, force: bool = True) -> bool: ...


@pytest.fixture
def create_project() -> ProjectMaker:
    def create(location: Path, force: bool = True) -> bool:
        ...

    return create


def test_project(create_project: ProjectMaker):
    project_created = create_project()
Run Code Online (Sandbox Code Playgroud)

不幸的是,PyCharm 目前不支持此功能(#PY-45438

  • “预期的方式似乎是”:似乎是根据谁的说法?如果这里有一些文档的链接那就太好了。 (9认同)