python有时候很麻烦的一点,为了运算速度,不给你做类型检查。这个特性被各路大佬当成重载的秘宝,但是有时候对工程性的项目来说并不安全。
这里介绍一个notice工具,会对函数形参标注类型和实参类型不一样时进行输出提醒(不报错,不影响运行)
1 from typing import get_type_hints
2 from functools import wraps
3 from inspect import getfullargspec
4
5 # 定义函数参数类型的检查函数
6 def parameter_check(obj, **kwargs):
7 hints = get_type_hints(obj)
8 for label_name, label_type in hints.items():
9 # print(label_name)
10 # print(label_type)
11 # 返回类型不检查 跳过 只检查实际传入参数的类型是否正确
12 if label_name == "return":
13 continue
14 # 判断实际传入的参数是否与函数标签中的参数一致
15 if not isinstance(kwargs[label_name], label_type):
16 print(f"参数:{label_name} 类型错误 应该为:{label_type}")
17
18 # 使用装饰器进行函数包裹
19 def wrapped_func(decorator):
20 @wraps(decorator)
21 def wrapped_decorator(*args, **kwargs):
22 func_args = getfullargspec(decorator)[0]
23 kwargs.update(dict(zip(func_args, args)))
24 parameter_check(decorator, **kwargs)
25 return decorator(**kwargs)
26 return wrapped_decorator
27
28 @wrapped_func
29 def add0(a: int, b: int) -> int:
30 return a + b
31
32
33 @wrapped_func
34 def add1(a: int, b: float = 520.1314) -> float:
35 return a + b
36
37 # print(add0(1, 1))
38 print(add0("hello", "world"))
运行结果如下图:
可以看出,进行函数包裹后,仍然能运行函数,只是运行前进行了类型检查和提醒。