validators.py 文件源码

python
阅读 34 收藏 0 点赞 0 评论 0

项目:packetary 作者: openstack 项目源码 文件源码
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
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号