1.0 KiB
1.0 KiB
Exercise 7.1 - Solution
# validate.py
...
from inspect import signature
def validated(func):
= signature(func)
sig
# Gather the function annotations
= dict(func.__annotations__)
annotations
# Get the return annotation (if any)
= annotations.pop('return', None)
retcheck
def wrapper(*args, **kwargs):
= sig.bind(*args, **kwargs)
bound = []
errors
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])except Exception as e:
f' {name}: {e}')
errors.append(
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
= func(*args, **kwargs)
result
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper