python - 如何将 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
我如何正确注释这个?我试过TypeVar
s 但我得到了同样的错误。
解决方案
直接分配类型提示,而不是让它通过函数注释分配。
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])
推荐阅读
- python - Django,让用户建立自己的表和数据结构
- vhdl - 开始...结束 VHDL 中的关键字对
- python - 无法在 pandas_profiling 上显示进度条
- google-apps-script - 根据谷歌表格中的单元格值自动填充单元格值
- spring - yaml文件中的star(*)有什么用?
- vue.js - 具有多个查询的过滤器的 Vue 路由
- c# - 带数组的搜索栏
- javascript - 使用 NextJS/Jest/Playwright 运行 e2e 测试
- openshift - 无法从 Openshift 访问 Jolokia 端点
- postman - Postman 无法在 Autodesk Forge 上获得 3LOath 的令牌