如何将 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 但我得到了同样的错误

解决方法

直接分配类型提示,而不是通过函数注解来分配。

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])