options.py 文件源码

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

项目:decorated_options 作者: musically-ut 项目源码 文件源码
def optioned(option_arg='_opts'):
    """Returns a decorator which can 'fill-in' the arguments to function 'f' using the
    option passed in with the name given by `option_arg` parameter.

    :param: option_arg: The name of the argument which will contain the Options object.
    """
    def _decorator(f):
        sig = inspect.signature(f)
        params = sig.parameters
        f_args = params.keys()

        @wraps(f)
        def wrapped_f(*args, **kwargs):
            if option_arg not in kwargs:
                return f(*args, **kwargs)
            else:
                opts = kwargs[option_arg]
                all_args_dict = opts._get_dict()
                all_args_dict.update(kwargs)

                new_arg_dict = {}
                for idx, arg in enumerate(f_args):
                    if idx < len(args):
                        # This argument was passed positionally, ignore
                        pass
                    else:
                        if arg in all_args_dict:
                            new_arg_dict[arg] = all_args_dict[arg]
                        elif params[arg].default is not inspect._empty:
                            new_arg_dict[arg] = params[arg].default

                return f(*args, **new_arg_dict)

        return wrapped_f

    return _decorator
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号