微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何将 MyPy 作为参数接受的类型提示传递给内部定义函数的函数?

如何解决如何将 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])

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。