对python函数进行强制类型检查,提升安全性。需要的请直接复制。
1.设置类型注解
2.增加装饰器
def force_type_check(func):
annotations = func.__annotations__
def wrapper(*args, **kwargs):
for arg, value in zip(func.__code__.co_varnames, args):
target_type = annotations.get(arg, None)
if not target_type:
continue
if not isinstance(value, target_type):
raise TypeError(f"Argument '{arg}' must be of type '{annotations[arg].__name__}'")
return func(*args, **kwargs)
return wrapper
@force_type_check
def test(a: int, b: str, **kwargs):
print(a)
test(1, 2, c=3)
类型检查不通过时的运行效果