This commit is contained in:
Mike Bloy 2024-01-07 11:54:24 -06:00
parent cf6de58a63
commit 74498dc34b
3 changed files with 47 additions and 1 deletions

6
logcall.py Normal file
View File

@ -0,0 +1,6 @@
def logged(func):
print('Adding logging to', func.__name__)
def wrapper(*args, **kwargs):
print('Calling', func.__name__)
return func(*args, **kwargs)
return wrapper

11
sample.py Normal file
View File

@ -0,0 +1,11 @@
from logcall import logged
@logged
def add(x, y):
return x + y
@logged
def sub(x, y):
return x - y

View File

@ -66,6 +66,31 @@ class NonEmptyString(String, NonEmpty):
pass
def validated(func):
sig = inspect.signature(func)
annotations = dict(func.__annotations__)
retcheck = annotations.pop('return', None)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
class ValidatedFunction:
def __init__(self, func):
self.func = func
@ -83,6 +108,10 @@ class ValidatedFunction:
if __name__ == '__main__':
@validated
def add(x: Integer, y: Integer):
return x + y
add = ValidatedFunction(add)
@validated
def power(x: Integer, y: Integer):
return x ** y