Skip to content

Instantly share code, notes, and snippets.

@bkrmendy
Created November 11, 2018 23:14
Show Gist options
  • Save bkrmendy/26dd0035c33d744d0ed45949446de68f to your computer and use it in GitHub Desktop.
Save bkrmendy/26dd0035c33d744d0ed45949446de68f to your computer and use it in GitHub Desktop.
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