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

Function decorate

Solutions/7_3/validate.py:103–129  ·  view source on GitHub ↗
(func)

Source from the content-addressed store, hash-verified

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

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected