This article illustrates how Python examines function parameter data types through adorners. Share to everyone for your reference. The specific analysis is as follows:
This code defines a python adorner that can be used to check whether the parameters of the specified function are of the specified type, and adding this adorner when defining the function can be very clear to detect the type of function arguments, very handy
Copy Code code as follows:
def accepts (exception,**types):
Def check_accepts (f):
Assert len (types) = = F.func_code.co_argcount, \
' Accept number of arguments not equal with function number of arguments in '%s '% f.func_name
def new_f (*args, **kwds):
For i,v in Enumerate (args):
If Types.has_key (F.func_code.co_varnames[i]) and \
Not Isinstance (V, Types[f.func_code.co_varnames[i]]):
Raise exception ("Arg '%s ' =%r does not match%s"% \
(F.func_code.co_varnames[i],v,types[f.func_code.co_varnames[i]))
Del Types[f.func_code.co_varnames[i]]
For k,v in Kwds.iteritems ():
If Types.has_key (k) and not Isinstance (V, types[k]):
Raise exception ("Arg '%s ' =%r does not match%s"% \
(K,v,types[k])
Return f (*args, **kwds)
New_f.func_name = F.func_name
Return New_f
Return check_accepts
Def exmaple ():
@accepts (exception,a=int,b=list,c= (Str,unicode))
def test (A,b=none,c=none)
print ' OK '
Test (13,c=[],b= ' DF ')
I hope this article will help you with your Python programming.