I'd like to know your opinions on this minimal type-checking decorator (with @
annotations) to make type checking of a method while debugging like :
def typecheck(*tuples, **kwtuples):
def decorator(func):
def function_wrapper(*args, **kwargs):
#print('tuples : ' , tuples)
#print('kwtuples : ' , kwtuples)
#print('args : ' , args)
#print('kwargs : ' , kwargs)
for index, tup in enumerate(tuples):
arg = args[index]
if not isinstance(arg, tup):
raise ValueError('in ' + str(func.__name__) + ' : wrong argument on position ,' + str(index) + ' :' + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )
for key, tup in kwtuples.items():
arg = kwargs[key]
if not isinstance(args[index], tup):
raise ValueError('in ' + str(func.__name__) + ' : wrong argument ' + str(key) + ' :' + str(arg) + ' must be of type :' + str(tup) + 'but is' + str(type(arg)) )
#print("arguments: ", *args, **kwargs)
func(*args, **kwargs)
return function_wrapper
return decorator
@typecheck(str,(str, float))
def foo2(x,y):
print("Hi, foo has been called with ",str(x) ,y)
foo2('2',3.4)
The benefit of it is :
- Custom and detailed description about the wrong argument
- Later, you can extend this for custom validation like some item is in some range or structural inspection of an argument.
- Easy to write, apply and delete after testing (so it won't consume cpu time)
typing
and mypy/pyre/pyright/pytype for static type enforcement, you can also use something like pytypes for run-time type enforcement. \$\endgroup\$