def validate( narg, conv, logMessage = None ) :
def decorate( func) :
def funcDecorated( *args) :
newArgs = list ( args)
try :
newArgs[ narg] = conv( newArgs[ narg] )
except Exception , e:
# wrong argument! do some logging here and re-raise
raise Exception ( "Invalid argument #{}: {} {}" .format ( narg, e, "({})" .format ( logMessage) if logMessage else "" ) )
else :
return func( *newArgs)
return funcDecorated
return decorate
def customValidationFunction( value) :
if value % 2 == 0 :
return value
raise Exception ( "Value isn't even" )
@ validate( 0 , int )
@ validate( 1 , int , logMessage= 'argument must respond to int()' )
@ validate( 2 , customValidationFunction)
def some_func( int_arg, int_arg2, other_arg) :
# the control gets here only after args are validated correctly
return int_arg * int_arg2 * other_arg
def check( func) :
try :
func( )
except Exception , e:
return 'Wrong: {}' .format ( e)
else :
return 'OK'
print 1 , check( lambda : some_func( 5 , 10 , 2 ) )
print 2 , check( lambda : some_func( 'five' , 10 , 2 ) )
print 3 , check( lambda : some_func( 5 , 'ten' , 2 ) )
print 4 , check( lambda : some_func( 5 , 10 , 1 ) )
CgpkZWYgdmFsaWRhdGUobmFyZywgY29udiwgbG9nTWVzc2FnZSA9IE5vbmUpOgoJZGVmIGRlY29yYXRlKGZ1bmMpOgoJCWRlZiBmdW5jRGVjb3JhdGVkKCphcmdzKToKCQkJbmV3QXJncyA9IGxpc3QoYXJncykKCQkJdHJ5OgoJCQkJbmV3QXJnc1tuYXJnXSA9IGNvbnYobmV3QXJnc1tuYXJnXSkKCQkJZXhjZXB0IEV4Y2VwdGlvbiwgZToKCQkJCSMgd3JvbmcgYXJndW1lbnQhIGRvIHNvbWUgbG9nZ2luZyBoZXJlIGFuZCByZS1yYWlzZQoJCQkJcmFpc2UgRXhjZXB0aW9uKCJJbnZhbGlkIGFyZ3VtZW50ICN7fToge30ge30iLmZvcm1hdChuYXJnLCBlLCAiKHt9KSIuZm9ybWF0KGxvZ01lc3NhZ2UpIGlmIGxvZ01lc3NhZ2UgZWxzZSAiIikpCgkJCWVsc2U6CgkJCQlyZXR1cm4gZnVu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