[Python] python通过装饰器检查函数参数的数据类型 →→→→→进入此内容的聊天室

来自 , 2019-12-15, 写在 Python, 查看 100 次.
URL http://www.code666.cn/view/c7be03f5
  1. def accepts(exception,**types):
  2.     def check_accepts(f):
  3.         assert len(types) == f.func_code.co_argcount, \
  4.         'accept number of arguments not equal with function number of arguments in "%s"' % f.func_name
  5.         def new_f(*args, **kwds):
  6.             for i,v in enumerate(args):
  7.                 if types.has_key(f.func_code.co_varnames[i]) and \
  8.                     not isinstance(v, types[f.func_code.co_varnames[i]]):
  9.                     raise exception("arg '%s'=%r does not match %s" % \
  10.                         (f.func_code.co_varnames[i],v,types[f.func_code.co_varnames[i]]))
  11.                     del types[f.func_code.co_varnames[i]]
  12.  
  13.             for k,v in kwds.iteritems():
  14.                 if types.has_key(k) and not isinstance(v, types[k]):
  15.                     raise exception("arg '%s'=%r does not match %s" % \
  16.                         (k,v,types[k]))
  17.  
  18.             return f(*args, **kwds)
  19.         new_f.func_name = f.func_name
  20.         return new_f
  21.     return check_accepts
  22.  
  23.  
  24. def exmaple():
  25.  
  26.     @accepts(Exception,a=int,b=list,c=(str,unicode))
  27.     def test(a,b=None,c=None)
  28.         print 'ok'
  29.  
  30.     test(13,c=[],b='df')
  31. #//python/8977

回复 "python通过装饰器检查函数参数的数据类型"

这儿你可以回复上面这条便签

captcha