Created
November 11, 2018 23:14
-
-
Save bkrmendy/26dd0035c33d744d0ed45949446de68f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import inspect | |
def with_checks(checks): | |
def wrapper(func): | |
def wrapped(*args, **kwargs): | |
bound_args = inspect.signature(func).bind(*args, **kwargs) | |
errors = list() | |
for check in checks: | |
decorator_params = inspect.signature(check).parameters.keys() | |
matching_params = [(sym, bound_args.arguments[sym]) for sym in decorator_params if sym in bound_args.arguments.keys()] | |
if len(matching_params) > 0: | |
if not check(*[arg for _, arg in matching_params]): | |
errors.append(matching_params) | |
if len(errors) > 0: | |
raise ValueError("{fun}: argument(s) have bad value: {values}".format(fun=func.__name__, values=errors)) | |
return func(*args, **kwargs) | |
return wrapped | |
return wrapper | |
@with_checks([lambda a: a > -1, lambda b: b > -1]) | |
def addPositive(a,b): return a + b | |
@with_checks([lambda first_name: len(first_name) < 5, lambda last_name: len(last_name) < 7]) | |
def onlyShortNamePls(first_name, last_name): print("Hello there {first} {last}".format(first=first_name, last=last_name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment