作用
用于获取函数签名对象
基本用法
import inspect
# 待获取签名的函数
def func(x:int, y:str, z:list) -> None:
pass
# 获取签名对象,包括函数名,参数等
sig = inspect.signature(func)
print(sig)
# 获取签名中的参数,返回有序字典
params = sig.parameters
print(params)
# 通过循环并解构
for k, v in enumerate(params.items()):
name, param = v
print(param.annotation, param.kind, param.name)
# 获取签名中的返回值类型
ret = sig.return_annotation
print(ret)
例: 判断输入的实参是否为标注的类型
import datetime, time
import inspect
def check_str(func):
def wrapper(*args, **kwargs):
obj = inspect.signature(func)
params = obj.parameters
for k, v in enumerate(params.items()):
name, param = v
for i in args:
if not isinstance(i, param.annotation):
print("{}: {} is not string".format(name, i))
raise TypeError
ret = func(*args, **kwargs)
return ret
return wrapper
@check_str
def str_add(str1:str, str2:str):
t1 = datetime.datetime.now()
new_str = str1 + str2
time.sleep(3)
delta_time = (datetime.datetime.now() - t1).total_seconds()
print(new_str, round(delta_time), sep="\n")
str_add(3, "4")