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

Function decorate

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

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected