# -*- coding: utf-8 -*-
# by dl
from inspect import signature # 用来获取函数的一些信息
# 自定义参数验证装饰器
def typeassert(*ty_args, **ty_kargs):
def decorator(func):
# 获取传入参数的签名对象
sig = signature(func)
# 把 传入自定义装饰器的参数拿下来 建立映射
btypes = sig.bind_partial(*ty_args, **ty_kargs).arguments
print('btypes', btypes)
def wrapper(*args, **kargs):
print(sig.bind(*args, **ty_kargs).arguments.items())
for name, obj in sig.bind(*args, **ty_kargs).arguments.items():
print('name', name)
print('obj', obj)
# 只有属于btypes(字典类型)才进行类型检查
if name in btypes:
if name in btypes:
if not isinstance(obj, btypes[name]):
raise TypeError('%s must be %s' % (name, btypes[name]))
# 查看参数是否在字典 然后判断类型
return func(*args, **kargs)
return wrapper
return decorator
@typeassert(int, str, list)
def f(a, b, c):
print(a, b, c)
f(1, 'abc', [1, 2, 3])
f(1, 2, [1, 2, 3])