Python uses the decorator to check the data type of function parameters

Source: Internet
Author: User
Tags python decorator
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.