def declare_schema(**schemas):
"""Declares data schema for function arguments.
:param schemas: the mapping, where key is argument name, value is schema
the schema may be callable object or method of class
in this case the wrapped function should be method of
same class
:raises ValueError: if the passed data does not fit declared schema
"""
def decorator(func):
validators = {k: _build_validator(v) for k, v in schemas.items()}
defaults = _get_default_arguments(func)
@functools.wraps(func)
def wrapper(*args, **kwargs):
bound_args = inspect.getcallargs(func, *args, **kwargs)
for n, v in bound_args.items():
if v is not defaults.get(n, _SENTINEL) and n in validators:
validators[n](args and args[0] or None, v)
return func(*args, **kwargs)
return wrapper
return decorator
评论列表
文章目录