如何告知mypy我是在刻意测试错误类型的输入?
针对mypy忽略错误类型测试的解决方案
一、让mypy忽略特定行的报错
要让mypy忽略该行的类型错误,最直接的方式是在代码行末尾添加精准的忽略注释:
add("foo") # type: ignore[arg-type]
- 使用
[arg-type]可以精准指定忽略的错误类型,避免无差别忽略所有类型问题,保证其他类型检查仍能正常运行。 - 如果需要忽略该行所有mypy错误,也可以简化为
# type: ignore,但不推荐这种全局忽略的方式,容易漏掉真正的类型问题。
二、测试错误输入类型的Pythonic方式
方式1:使用typing.cast显式强制类型转换
通过cast告诉mypy我们刻意将错误类型转换为函数期望的类型,既满足测试需求,又不破坏整体类型检查:
import pytest from typing import cast def add(a: float) -> float: if not isinstance(a, float): raise ValueError("a must be of type float") return 10 + a def test_add_wrong_type() -> None: with pytest.raises(ValueError) as err: add(cast(float, "foo")) # 显式告知mypy强制转换类型 assert str(err.value) == "a must be of type float"
方式2:调整函数的类型标注(适合需接受任意输入的场景)
如果你的函数设计目标就是接受任意类型输入,再做内部类型校验,可以将参数类型标注为Any:
import pytest from typing import Any def add(a: Any) -> float: if not isinstance(a, float): raise ValueError("a must be of type float") return 10 + a def test_add_wrong_type() -> None: with pytest.raises(ValueError) as err: add("foo") # 此时mypy不会报错 assert str(err.value) == "a must be of type float"
这种方式适合函数确实需要处理任意输入的场景,类型标注更贴合函数实际行为。
方式3:针对测试目录配置mypy规则
可以在项目的mypy.ini(或pyproject.toml)中,对测试目录设置宽松的类型检查规则,比如关闭arg-type检查:
[mypy-tests.*] disable_error_codes = arg-type
这种方式适合所有测试用例都需要忽略同类错误的场景,但范围较大,需谨慎使用。
内容的提问来源于stack exchange,提问作者Andi
相关产品推荐
相关产品推荐

