Last active
June 5, 2026 10:20
-
-
Save allynt/ece5104d2d2c84c83de30d6b9d44809b to your computer and use it in GitHub Desktop.
generic function argument validation decorator
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 | |
| from inspect import signature | |
| def validate_arguments(validators): | |
| """ | |
| Decorator for function to validate passed arguments | |
| :param validators: mapping of argument names to validation functions | |
| """ | |
| def decorator(fn): | |
| fn_params = signature(fn).parameters | |
| # make sure the specified argument is in the fn signature... | |
| assert set(validators) <= set(fn_params), f"invalid validator for {str(fn)}" | |
| @wraps(fn) | |
| def wrapper(*args, **kwargs): | |
| # check if any args should be validated... | |
| for arg_name, arg_value in zip(fn_params, args): | |
| if arg_name in validators: | |
| arg_validator = validators.pop(arg_name) | |
| if not arg_validator(arg_value): | |
| raise RuntimeErorr(f"invalid argument to {str(fn)}: {arg_name}") | |
| if validators: | |
| # if there are still validators remaining, check if any kwargs should be validated... | |
| for kwarg_name, kwarg_value in kwargs.items(): | |
| if kwarg_name in validators: | |
| kwarg_validator = validators.pop(kwarg_name) | |
| if not kwarg_validator(kwarg_value): | |
| raise RuntimeError(f"invalid argument to {str(fn)}: {kwarg_name}") | |
| # validation passed - run the function... | |
| result = fn(*args, **kwargs) | |
| return result | |
| return wrapper | |
| return decorator |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment