【发布时间】:2020-11-25 15:54:52
【问题描述】:
我正在尝试编写我的一个 python 装饰器来进行类型检查。它工作得很好,但在嵌套类型提示方面遇到了困难。例如采取
@type_check
def fun(x: int) -> List[List[List[str]]]:
return [[[str(x)]]]
fun(x=42)
我有一个装饰器,它评估函数并检查实际返回值是否具有预期的类型:
import inspect
# inside the decorator
actual_result = func(*args, **kwargs) # [[['42']]]
expected_result_type = spec.annotations['return'] # typing.List[typing.List[typing.List[str]]]
现在要检查的是[[['42']]] 的类型为typing.List[typing.List[typing.List[str]]]。
我该怎么做?
我发现,[[['42']]] 只需键入<class 'list'>,它完全忽略了有关嵌套的信息。
我可以检查一下
if hasattr(expected_result_type, '__origin__'):
expected_result_type = expected_result_type.__origin__
if expected_result_type is not None:
assert isinstance(result, expected_result_type)
else: # None is kind of a special case
assert result is expected_result_type
这适用于“外层”,但忽略嵌套类型提示。有什么方法可以检查所有图层吗?
【问题讨论】:
标签: python python-3.x python-decorators python-typing