fork(1) download
  1.  
  2.  
  3. def validate(narg, conv, logMessage = None):
  4. def decorate(func):
  5. def funcDecorated(*args):
  6. newArgs = list(args)
  7. try:
  8. newArgs[narg] = conv(newArgs[narg])
  9. except Exception, e:
  10. # wrong argument! do some logging here and re-raise
  11. raise Exception("Invalid argument #{}: {} {}".format(narg, e, "({})".format(logMessage) if logMessage else ""))
  12. else:
  13. return func(*newArgs)
  14.  
  15. return funcDecorated
  16. return decorate
  17.  
  18. def customValidationFunction(value):
  19. if value % 2 == 0:
  20. return value
  21. raise Exception("Value isn't even")
  22.  
  23. @validate(0, int)
  24. @validate(1, int, logMessage='argument must respond to int()')
  25. @validate(2, customValidationFunction)
  26. def some_func(int_arg, int_arg2, other_arg):
  27. # the control gets here only after args are validated correctly
  28. return int_arg * int_arg2 * other_arg
  29.  
  30.  
  31. def check(func):
  32. try:
  33. func()
  34. except Exception, e:
  35. return 'Wrong: {}'.format(e)
  36. else:
  37. return 'OK'
  38.  
  39. print 1, check(lambda: some_func(5,10,2))
  40. print 2, check(lambda: some_func('five',10,2))
  41. print 3, check(lambda: some_func(5,'ten',2))
  42. print 4, check(lambda: some_func(5,10,1))
  43.  
Success #stdin #stdout 0.08s 10864KB
stdin
Standard input is empty
stdout
1 OK
2 Wrong: Invalid argument #0: invalid literal for int() with base 10: 'five' 
3 Wrong: Invalid argument #1: invalid literal for int() with base 10: 'ten' (argument must respond to int())
4 Wrong: Invalid argument #2: Value isn't even