函数参数类型校验装饰器

Posted on 2022-11-27 21:20  呱呱呱呱叽里呱啦  阅读(23)  评论(0编辑  收藏  举报

函数参数类型校验装饰器

from functools import wraps
from inspect import getfullargspec


def validate_detail(fuc, **kwargs):
    expected_info = fuc.__annotations__
    for para_name, para_type in expected_info.items():
        if para_name == 'return':
            continue
        if not isinstance(kwargs[para_name], para_type):
            raise TypeError(f'函数{fuc.__name__}的参数{para_name}被传入错误值{kwargs[para_name]}, 该参数类型应为{para_type}')


def validate_func_paras(decorator):
    @wraps(decorator)
    def wrapped_decorator(*args, **kwargs):
        func_args = getfullargspec(decorator)[0]
        kwargs.update(dict(zip(func_args, args)))
        validate_detail(decorator, **kwargs)
        return decorator(**kwargs)

    return wrapped_decorator

测试代码

@validate_func_paras
def add(a: str, b: str) -> str:
    return a + b


add(1, 2)

'''
Traceback (most recent call last):
  File "D:\test\pycharm_test\参数检查.py", line 30, in <module>
    add(1, 2)
  File "D:\test\pycharm_test\参数检查.py", line 19, in wrapped_decorator
    validate_detail(decorator, **kwargs)
  File "D:\test\pycharm_test\参数检查.py", line 11, in validate_detail
    raise TypeError(f'函数{fuc.__name__}的参数{para_name}被传入错误值{kwargs[para_name]}, 该参数类型应为{para_type}')
TypeError: 函数add的参数a被传入错误值1, 该参数类型应为<class 'str'>
'''