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

Function validated

Solutions/7_1/validate.py:63–97  ·  view source on GitHub ↗
(func)

Source from the content-addressed store, hash-verified

61 return isinstance(item, type) and issubclass(item, Validator)
62
63def 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 def wrapper(*args, **kwargs):
74 bound = sig.bind(*args, **kwargs)
75 errors = []
76
77 # Enforce argument checks
78 for name, validator in annotations.items():
79 try:
80 validator.check(bound.arguments[name])
81 except Exception as e:
82 errors.append(f' {name}: {e}')
83
84 if errors:
85 raise TypeError('Bad Arguments\n' + '\n'.join(errors))
86
87 result = func(*args, **kwargs)
88
89 # Enforce return check (if any)
90 if retcheck:
91 try:
92 retcheck.check(result)
93 except Exception as e:
94 raise TypeError(f'Bad return: {e}') from None
95 return result
96
97 return wrapper
98
99# Examples
100if __name__ == '__main__':

Callers

nothing calls this directly

Calls 1

isvalidatorFunction · 0.70

Tested by

no test coverage detected