根据命名约定检查函数参数类型
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了根据命名约定检查函数参数类型相关的知识,希望对你有一定的参考价值。
not an answer for everything, but perhaps for basic types
from types import * def bfnCheckArgTypes(*args): sErr = "" # loops through: ('sString', 'tupTuple', 'iInteger', 'lstList') for iInd, sArgName in enumerate(args[0].func_code.co_varnames): if sArgName.startswith("tup") and not type(args[iInd+1]) is TupleType: sErr += " arg '%s' is not of type 'tuple'" % sArgName elif sArgName.startswith("lst") and not type(args[iInd+1]) is ListType: sErr += " arg '%s' is not of type 'list'" % sArgName elif sArgName.startswith("i") and not type(args[iInd+1]) is IntType: sErr += " arg '%s' is not of type 'int'" % sArgName elif sArgName.startswith("s") and not type(args[iInd+1]) is StringType: sErr += " arg '%s' is not of type 'str'" % sArgName if not sErr == "": print "Function '%s' has argument errors: %s" % (args[0].__name__, sErr) return False return True def fnTestMe(sString, tupTuple, iInteger, lstList): assert bfnCheckArgTypes(fnTestMe, sString, tupTuple, iInteger, lstList) # Test the code with these: fnTestMe("string-OK", ("tuple","OK"), 55, ["list","OK"]) # all OK #fnTestMe("string-OK", "notTuple", 55, "notList") # 2nd and 4th fail fnTestMe(55, ("tuple","OK"), "string-NOK", ["list","OK"]) # 1st and 3rd fail
以上是关于根据命名约定检查函数参数类型的主要内容,如果未能解决你的问题,请参考以下文章