MCPcopy
hub / github.com/dabeaz-course/python-mastery / validated

Function validated

Solutions/7_6/validate.py:68–103  ·  view source on GitHub ↗
(func)

Source from the content-addressed store, hash-verified

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

Callers 1

validate_attributesFunction · 0.90

Calls 1

isvalidatorFunction · 0.70

Tested by

no test coverage detected