from inspect import signature
def typeassert(*ty_args, **ty_kwargs): def decorator(func): def wapper(*args, **kwargs): return func(*args, **kwargs) return wapper return decorator
def f(a, b, c): pass sig = signature(f) print(sig.parameters) ''' 返回参数的字典 OrderedDict([('a', <Parameter "a">), ('b', <Parameter "b">), ('c', <Parameter "c">)]) ''' a = sig.parameters['a'] print(a.name) print(a.kind) print(a.default)
print(sig.bind) ''' <bound method Signature.bind of <Signature (a, b, c)>> '''
bargs = sig.bind(str, int, int) print(bargs) print(bargs.arguments) ''' <BoundArguments (a=<class 'str'>, b=<class 'int'>, c=<class 'int'>)> OrderedDict([('a', <class 'str'>), ('b', <class 'int'>), ('c', <class 'int'>)]) ''' print(bargs.arguments['a']) print(bargs.arguments['b']) print(bargs.arguments['c']) bargs.bind_partial()
from inspect import signature
def typeassert(*ty_args, **ty_kwargs): def decorator(func): sig = signature(func) btypes = sig.bind_partial(*ty_args, **ty_kwargs).arguments '''绑定的类型 某些参数不做类型检查不会报错 '''
def wapper(*args, **kwargs): for name, obj in sig.bind(*args, **kwargs).arguments.items(): ''' 获得到绑定的参数 类型对其进行迭代 ''' if name in btypes: if not isinstance(obj, btypes[name]): raise TypeError("{} must be {}".format(name, btypes[name])) return func(*args, **kwargs) return wapper return decorator
@typeassert(int, str, list) def f(a, b, c): print(a, b, c) f(1, '2', []) f(1,2,3) ''' raise TypeError("{} must be {}".format(name, btypes[name])) TypeError: b must be <class 'str'> '''
|