Checking function argument types against naming convention


/ Published in: Python
Save to your folder(s)

not an answer for everything, but perhaps for basic types


Copy this code and paste it in your HTML
  1. from types import *
  2.  
  3. def bfnCheckArgTypes(*args):
  4. sErr = ""
  5. # loops through: ('sString', 'tupTuple', 'iInteger', 'lstList')
  6. for iInd, sArgName in enumerate(args[0].func_code.co_varnames):
  7. if sArgName.startswith("tup") and not type(args[iInd+1]) is TupleType:
  8. sErr += "\n arg '%s' is not of type 'tuple'" % sArgName
  9. elif sArgName.startswith("lst") and not type(args[iInd+1]) is ListType:
  10. sErr += "\n arg '%s' is not of type 'list'" % sArgName
  11. elif sArgName.startswith("i") and not type(args[iInd+1]) is IntType:
  12. sErr += "\n arg '%s' is not of type 'int'" % sArgName
  13. elif sArgName.startswith("s") and not type(args[iInd+1]) is StringType:
  14. sErr += "\n arg '%s' is not of type 'str'" % sArgName
  15. if not sErr == "":
  16. print "Function '%s' has argument errors: %s" % (args[0].__name__, sErr)
  17. return False
  18. return True
  19.  
  20.  
  21. def fnTestMe(sString, tupTuple, iInteger, lstList):
  22. assert bfnCheckArgTypes(fnTestMe, sString, tupTuple, iInteger, lstList)
  23.  
  24.  
  25. # Test the code with these:
  26.  
  27. fnTestMe("string-OK", ("tuple","OK"), 55, ["list","OK"]) # all OK
  28.  
  29. #fnTestMe("string-OK", "notTuple", 55, "notList") # 2nd and 4th fail
  30.  
  31. fnTestMe(55, ("tuple","OK"), "string-NOK", ["list","OK"]) # 1st and 3rd fail

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.