def validate_input(obj, **kwargs): hints = get_type_hints(obj) for para_name, para_type in hints.items(): if para_name == "return": continue if not isinstance(kwargs[para_name], para_type): raise TypeError("参数:{}类型错误,应该是{}".format(para_name, para_type))
def type_check(decorator): @wraps(decorator) def wrapper_decorator(*args, **kwargs): func_args = getfullargspec(decorator)[0] kwargs.update(dict(zip(func_args, args))) validate_input(decorator, **kwargs) return decorator(**kwargs) return wrapper_decorator
@type_check def add(a: int, b: int) -> int: return a + b if __name__ == ‘__main__‘: print(add(18, "sss")) # from typing import get_type_hints # # print(add.__annotations__) # print(get_type_hints(add))
原文:https://www.cnblogs.com/tracydzf/p/14891563.html