Python examines the method of function parameter data types through adorners _python

Source: Internet
Author: User

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.

Related Article

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.