Last active
April 21, 2019 05:36
-
-
Save gyli/a986c8ee34544cbcf1aa to your computer and use it in GitHub Desktop.
Parameter Validator with decorator
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
def accepts(*types): | |
def check_accepts(f): | |
assert len(types) == f.func_code.co_argcount | |
def new_f(*args, **kwds): | |
for (a, t) in zip(args, types): | |
assert isinstance(a, t), "arg %r does not match %s" % (a, t) | |
return f(*args, **kwds) | |
new_f.func_name = f.func_name | |
return new_f | |
return check_accepts | |
def par_validator(par_values): | |
def check_accepts(f): | |
def new_f(*args, **kwds): | |
for k, v in par_values.iteritems(): | |
assert kwds[k] in v | |
return f(*args, **kwds) | |
new_f.func_name = f.func_name | |
return new_f | |
return check_accepts | |
@accepts(int, (int, float), str) | |
@par_validator({'arg2': [2, 3], 'arg3': ['par3_1', 'par3_2']}) | |
def func(arg1, arg2, arg3): | |
return | |
func(arg1=3, arg2=2, arg3='par3_2') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment