首页 > 解决方案 > 如何将 MyPy 将接受的类型提示作为参数传递给在内部定义函数的函数?

问题描述

我正在尝试为我们与beartype 一起使用的类型编写单元测试,我们的运行时类型检查器。测试按预期运行,但 MyPy 不会接受代码。

以下代码有效,但 MyPy 检查失败。

def typecheck(val: Any, t: type):
    """
    isinstance() does not allow things like Tuple[Int]
    """

    @beartype
    def f(v: t):
        return v

    try:
        f(val)
    except BeartypeCallHintPepParamException:
        return False
    return True

# passes
def test_typecheck():
    assert typecheck((1,), Tuple[int])
    assert not typecheck((1,), Tuple[str])

但是,我收到以下错误。链接到页面没有帮助。

error: Variable "t" is not valid as a type
note: See https://mypy.readthedocs.io/en/latest/common_issues.html#variables-vs-type-aliases

我如何正确注释这个?我试过TypeVars 但我得到了同样的错误。

标签: pythontype-hintingmypy

解决方案


直接分配类型提示,而不是让它通过函数注释分配。

def typecheck(val, t):
    """
    isinstance() does not allow things like Tuple[Int]
    """

    @beartype
    def f(v):
        return v
    f.__annotations__['v'] = t

    try:
        f(val)
    except BeartypeCallHintPepParamException:
        return False
    return True

# passes
def test_typecheck():
    assert typecheck((1,), Tuple[int])
    assert not typecheck((1,), Tuple[str])

推荐阅读