python函数类型检查

from functools import wraps
from inspect import getfullargspec
from typing import get_type_hints


def validate_input(obj, **kwargs):
    hints = get_type_hints(obj)
    print(hints)
    for parm_name, parm_type in hints.items():
        if parm_name == 'return':
            continue
        if not isinstance(kwargs[parm_name], parm_type):
            raise TypeError("参数:{}类型错误,应该是{}".format(parm_name, parm_type))
    
def type_check(decorator):
    @wraps(decorator)
    def wrapper(*args, **kwargs):
        # 获取func的虚参的名称 ['a', 'b']
        func_args = getfullargspec(decorator)[0]
        print(func_args, args, kwargs)
        # ["a": 1, "b": 2]
        kwargs.update(dict(zip(func_args, args)))
        print(kwargs)
        validate_input(decorator, **kwargs)
        return decorator(**kwargs)
    return wrapper

    
    
@type_check
def func(a: int, b: int) -> int:
    return a + b


print(func(1, b=5))

你可能感兴趣的:(python,python,开发语言,后端)