This article mainly introduces how to check the data type of function parameters through the decorator in python. it involves the usage skills of the Python decorator and has some reference value, for more information about how to check the data type of function parameters, see the example in this article. Share it with you for your reference. The specific analysis is as follows:
This code defines a python modifier that can be used to check whether the parameter of a specified function is of the specified type, adding this decorator when defining a function can clearly check the type of function parameters, which is very convenient.
The code is 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 Python programming.