Last active
November 21, 2017 20:37
-
-
Save AndresMWeber/e46f2b021840a35b3720fe4c951dfd71 to your computer and use it in GitHub Desktop.
Input Validator Abstraction
This file contains hidden or 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
from functools import wraps | |
def verify_inputs(filterers=None, validators=None): | |
""" Verify the inputs going into any function with equal length lists of: | |
filterers (for filtering out objects we do not care about) and | |
validators (to check the object itself is valid). | |
""" | |
filterers = filterers if filterers is not None else [] | |
validators = validators if validators is not None else [] | |
def decorator(function): | |
@wraps(function) | |
def wrapper(*args, **kwargs): | |
check_inputs = [] | |
for function_input in args + [v for k, v in iteritems(kwargs)]: | |
for filterer in filterers: | |
if filterer(function_input): | |
check_inputs.append(function_input) | |
for check_input in check_inputs: | |
for validator, filterer in zip(validators, filterers): | |
if filterer(check_input): | |
validator(check_input) | |
return function(*args, **kwargs) | |
return wrapper | |
return decorator |
Updated with functools.wraps implementation. I keep forgetting about that helpful little one. Gonna implement a bit better around validator/filter pairs now.
Added slightly better validation...still not convinced it's a great way to do it.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
check out https://docs.python.org/2/library/functools.html#functools.wraps