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

Function enforce

Solutions/9_2/structly/validate.py:105–135  ·  view source on GitHub ↗
(**annotations)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected