Ex 7.1
This commit is contained in:
parent
cf6de58a63
commit
74498dc34b
6
logcall.py
Normal file
6
logcall.py
Normal 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
11
sample.py
Normal 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
|
||||||
31
validate.py
31
validate.py
@ -66,6 +66,31 @@ class NonEmptyString(String, NonEmpty):
|
|||||||
pass
|
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:
|
class ValidatedFunction:
|
||||||
def __init__(self, func):
|
def __init__(self, func):
|
||||||
self.func = func
|
self.func = func
|
||||||
@ -83,6 +108,10 @@ class ValidatedFunction:
|
|||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
|
@validated
|
||||||
def add(x: Integer, y: Integer):
|
def add(x: Integer, y: Integer):
|
||||||
return x + y
|
return x + y
|
||||||
add = ValidatedFunction(add)
|
|
||||||
|
@validated
|
||||||
|
def power(x: Integer, y: Integer):
|
||||||
|
return x ** y
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user