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

标签 python python-3.x pycharm pytest

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

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

    return create


def test_project(create_project):
    project_created = create_project()
enter image description here
使用给定的类型提示:
@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()
enter image description hereCallable 的另一个问题也就是说,我必须在 fixture 中以及在我使用该 fixture 的每个测试中描述一次参数和返回类型。
那么有没有更有效的方法呢?

最佳答案

预期的方式似乎是使用 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()
不幸的是,目前 PyCharm 不支持此功能 ( #PY-45438 )

关于python - 返回方法的 pytests 固定装置的类型提示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66079261/

相关文章:

python - 调整 pcolormesh 颜色条以关注特定绘图区域?

python - 如何从列表中删除与同一列表中的其他字符串具有相同单词集(顺序困惑)的字符串

pycharm - Pycharm for Robot 框架中的自动完成

pycharm - pycharm持续连接到控制台的原因是什么

Python 从缓冲区播放声音

python - FacetGrid 上的 Seaborn 颜色条用于具有标准化颜色映射的 histplot

python - __init__ 文件在 python 中没有按预期工作

python-3.x - 如何在文本文件的第二行上写而忽略第一行?

python-3.x - 使用 BeautifulSoup 提取标题

python - PyCharm 在读取文件时不输出文本