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

Function enforce

Solutions/7_4/validate.py:99–129  ·  view source on GitHub ↗
(**annotations)

Source from the content-addressed store, hash-verified

97 return wrapper
98
99def enforce(**annotations):
100 retcheck = annotations.pop('return_', None)
101
102 def decorate(func):
103 sig = signature(func)
104
105 @wraps(func)
106 def wrapper(*args, **kwargs):
107 bound = sig.bind(*args, **kwargs)
108 errors = []
109
110 # Enforce argument checks
111 for name, validator in annotations.items():
112 try:
113 validator.check(bound.arguments[name])
114 except Exception as e:
115 errors.append(f' {name}: {e}')
116
117 if errors:
118 raise TypeError('Bad Arguments\n' + '\n'.join(errors))
119
120 result = func(*args, **kwargs)
121
122 if retcheck:
123 try:
124 retcheck.check(result)
125 except Exception as e:
126 raise TypeError(f'Bad return: {e}') from None
127 return result
128 return wrapper
129 return decorate
130
131# Examples
132if __name__ == '__main__':

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected