(func)
| 61 | return isinstance(item, type) and issubclass(item, Validator) |
| 62 | |
| 63 | def validated(func): |
| 64 | sig = signature(func) |
| 65 | |
| 66 | # Gather the function annotations |
| 67 | annotations = { name:val for name, val in func.__annotations__.items() |
| 68 | if isvalidator(val) } |
| 69 | |
| 70 | # Get the return annotation (if any) |
| 71 | retcheck = annotations.pop('return', None) |
| 72 | |
| 73 | @wraps(func) |
| 74 | def wrapper(*args, **kwargs): |
| 75 | bound = sig.bind(*args, **kwargs) |
| 76 | errors = [] |
| 77 | |
| 78 | # Enforce argument checks |
| 79 | for name, validator in annotations.items(): |
| 80 | try: |
| 81 | validator.check(bound.arguments[name]) |
| 82 | except Exception as e: |
| 83 | errors.append(f' {name}: {e}') |
| 84 | |
| 85 | if errors: |
| 86 | raise TypeError('Bad Arguments\n' + '\n'.join(errors)) |
| 87 | |
| 88 | result = func(*args, **kwargs) |
| 89 | |
| 90 | # Enforce return check (if any) |
| 91 | if retcheck: |
| 92 | try: |
| 93 | retcheck.check(result) |
| 94 | except Exception as e: |
| 95 | raise TypeError(f'Bad return: {e}') from None |
| 96 | return result |
| 97 | |
| 98 | return wrapper |
| 99 | |
| 100 | def enforce(**annotations): |
| 101 | retcheck = annotations.pop('return_', None) |
no test coverage detected