A simple way to check Python parameter types __python

Source: Internet
Author: User
Python is a weakly typed language, and many of the friends who turn from C + + are not very comfortable at first. For example, when declaring a function, you cannot specify the type of the parameter. The analogy with C is that all parameters are void* types. Void type casts are widely considered to be a bad habit in C + + and will not be used unless you have to.

Python naturally does not have the type cast one says, because it is a dynamic language. First, all objects inherit from object, and second, it has a strong introspection, and if a method that does not exist is invoked, an exception is thrown. Most of the cases, we do not need to do the parameter type of the Bolt check, except for some special circumstances. For example, a function accepts a str type, the result is Unicode when the actual call is made, and no code is covered during the test, and the problem is more serious. The solution is also simple, with the help of Python introspection, it is easy to tell the type of the parameter. But it would be cumbersome to write and check the code everywhere, not to mention the actual value it brings. A good workaround is to use an adorner.

' >>> NONE, MEDIUM, strong = 0, 1, 2 >>> >>> @accepts (int, int, int) ... def average ( X, Y, z): ... return (x + y + z)/2 ... >>> average (5.5, 15.0) typewarning: ' Average ' method ac cepts (int, int, int), but was given (float, int, float) 15.25 ' Def accepts (*types, **kw): "" "Function Decorat Or.

    Checks that inputs given to decorated function are of the expected type.
             Parameters:types-The expected types of the inputs to the decorated function.
    Must specify type for each parameter.  KW-Optional specification of ' Debug ' level (this is the valid keyword argument, no other should to be
             given). debug = (0 | 1 | 2) "" "If not kw: # default Level:medium debug = 1 Else:debug =
                    kw[' Debug '] try:def decorator (f): Def NEWF (*args): if debug = = 0: return F (*args)
                Assert len (args) = = Len (types) argtypes = tuple (map (type, args)) if argty
                        PES!= types:msg = info (f.__name__, types, argtypes, 0) If debug = 1:
                        Print >> Sys.stderr, ' typewarning: ', msg elif debug = = 2:
        Raise TypeError, MSG return F (*args) newf.__name__ = f.__name__ return NEWF return decorator except Keyerror, Key:raise keyerror, key + ' not ' a valid keyword ' argument ' except T  Ypeerror, Msg:raise typeerror, msg def info (fname, expected, actual, flag): "" "Convenience function returns Nicely formatted error/warning msg. "" "format = Lambda types: ', '. Join ([str (t). Split (" ") [1] for T in types]) E xpected, actual = Format (expected), format (actual) msg = "'%s ' method"% fname \ + ("Accepts", "returns") [F LAG] + "(%s), but"% Expected\ + (' was given ', ' result is ') [flag] + ' (%s) '% actual return msg
 

In essence, this is also a run-time check, but the effect is good.
For more interesting use of adorners, you can refer to this article http://wiki.python.org/moin/PythonDecoratorLibrary


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.