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

Function enforce

Solutions/7_3/validate.py:100–130  ·  view source on GitHub ↗
(**annotations)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected