A simple way to implement parameter type checking in 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, you cannot specify the type of a parameter when declaring a function. The analogy with C is that all parameters are void* types! The void type cast is widely considered a bad habit in C + + and is not used as a last resort.

Python naturally does not have a type cast, because it is a dynamic language. First, all objects inherit from object, and second, it has strong introspection, and if a method that does not exist is called an exception is thrown. In most cases, we do not need to do the parameter type suppository, except for some special cases. For example, if a function accepts a str type, the result is Unicode when it is actually called, and no code is overwritten during the test, so the problem is more serious. The solution is also simple, with Python's introspection, which makes it easy to determine the type of the parameter. But it is cumbersome to write check code everywhere, not to mention the actual value it brings. A good workaround is to use adorners.

' >>> 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 accepts (int, int, in T), but is given (float, int, float) 15.25 "Def accepts (*types, **kw):" "Function decorator.  Checks that inputs given to decorated function is 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 was the only valid keyword argument, no other should 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 (ty PES) argtypes = tuple (map (type, args)) if argtypes! = 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 + "is not a valid keyword argument" except Typeer Ror, Msg:raise TypeError, msgdef info (fname, expected, actual, flag): "" "convenience function returns nicely Formatt Ed error/warning msg. "" "format = Lambda types: ', '. Join ([str (t). Split (" ' ") [1] for T in types]) expected, actual = for Mat (expected), format (actual) msg = "'%s ' method"% fname \ + ("Accepts", "returns") [flag] + "(%s), but"% expecte D\ + ("was given", "result is") [flag] + "(%s)"% actual return msg

Essentially, this is a run-time check, but the effect is good.
For more interesting use of adorners, 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.