我的一些 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()
使用给定的类型提示:
@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()
Callable
的另一个问题也就是说,我必须在 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/