Skip to content

Instantly share code, notes, and snippets.

@AndresMWeber
Last active November 21, 2017 20:37
Show Gist options
  • Save AndresMWeber/e46f2b021840a35b3720fe4c951dfd71 to your computer and use it in GitHub Desktop.
Save AndresMWeber/e46f2b021840a35b3720fe4c951dfd71 to your computer and use it in GitHub Desktop.
Input Validator Abstraction
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
@ssttuu
Copy link

ssttuu commented Nov 21, 2017

@AndresMWeber
Copy link
Author

Updated with functools.wraps implementation. I keep forgetting about that helpful little one. Gonna implement a bit better around validator/filter pairs now.

@AndresMWeber
Copy link
Author

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