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

Function validated

Solutions/7_2/validate.py:64–99  ·  view source on GitHub ↗
(func)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls 1

isvalidatorFunction · 0.70

Tested by

no test coverage detected