Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/350.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何为pytest装置指定mypy类型_Python_Pytest_Mypy - Fatal编程技术网

Python 如何为pytest装置指定mypy类型

Python 如何为pytest装置指定mypy类型,python,pytest,mypy,Python,Pytest,Mypy,我正在尝试为我在测试项目中使用的pytest本机装置指定mypy类型提示,例如: import pytest def pytest_configure(config): # Do something useful here configfixture返回一个\u pytest.config.config对象。如果我尝试天真地对此建模: import pytest def pytest_configure(config: Config) -> None: # Do so

我正在尝试为我在测试项目中使用的pytest本机装置指定mypy类型提示,例如:

import pytest

def pytest_configure(config):
    # Do something useful here
config
fixture返回一个
\u pytest.config.config
对象。如果我尝试天真地对此建模:

import pytest

def pytest_configure(config: Config) -> None:
    # Do something useful here
我收到一个mypy错误:
conftest.py:3:错误:未定义名称“Config”[名称已定义]


我可以从_pytest.config import config执行
,但这似乎不是一个好方法,因为_pytest是私有的。
另一个选项是使用
忽略类型#type:ignore
。如果这是推荐的方法,我当然会这样做,但我想知道是否有更好的选择

我使用的任何类型的pytest本机fixture都有相同的问题,例如用于参数化fixture的
request
。这将是一个
\u pytest.fixtures.FixtureRequest

导入


由于
pytest
当前不导出
Config
(从6.2开始),因此键入的唯一方法是使用
从_pytest.Config导入Config
。这也是我键入
config
的方式,例如可以在以下内容中看到:

您可以在此
pytest
问题中跟踪键入进度:

自定义类型存根 您还可以引入一个小的自定义类型存根来隐藏重新导出。它在这里是否有用还值得商榷,只是值得一提的另一种解决方案。如果创建包含以下内容的文件
\u typeshed/pytest.pyi

from typing import Any
from _pytest.config import Config as Config

def __getattr__(name: str) -> Any: ...  # incomplete
并使其可访问
mypy.ini
中的
mypy

[mypy]
mypy_path = _typeshed
现在至少可以在类型检查模式下从pytest import Config导入
,运行时导入仍然会失败。所以进口看起来像

from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from pytest import Config
else:
    Config = Any


def pytest_configure(config: Config) -> None:
    pass

该解决方案的唯一好处是现在隐藏了私有导入;尽管如此,我还是会使用私有导入。

从_pytest.config导入配置
是一种方式,因为由于某些原因,
配置
不是由
pytest
ATM导出的。不过,请随意。对于
请求
键入、签出和相关内容。谢谢,如果您将此作为答案,我将接受。开的
from typing import Any, TYPE_CHECKING

if TYPE_CHECKING:
    from pytest import Config
else:
    Config = Any


def pytest_configure(config: Config) -> None:
    pass