【问题标题】:Decorating decorators and the Click python library装饰装饰器和 Click python 库
【发布时间】:2019-09-03 14:32:58
【问题描述】:

我正在尝试将装饰器与 Click 框架一起使用来执行多个命令共有的工作,而无需在组的根元素中使用参数(请参阅 https://github.com/pallets/click/issues/295 了解原因)。简而言之,是这样的:

@click.group()
def main():
  pass

@main.command()
@click.option('--argument-a')
@parse_config_file
@init_session
def do_something_in_session(argument_a, config, session):
   # code
   return

装饰器也有参数:

def init_session(f):
  @wraps(f)
  @click.option('--argument-B')
  def wrapper(*args, **kwargs):
    # do something with argument-B, and add session to list of arguments.
    del kwargs['argument-B']
    kwargs['session'] = session_created_above

    return f(*args,**kwargs)
  return wrapper

def parse_config_file(f):
  @wraps(f)
  @click.option('--argument-C')
  def wrapper(*args, **kwargs):
    # do something with argument-C, and add config to list of arguments.
    del kwargs['argument-C']
    kwargs['config'] = config_parsed_above

    return f(*args,**kwargs)
  return wrapper

但是,当运行do_something_in_session --help 时,仅显示函数定义上方的装饰器的参数,在本例中为@init_session。有没有办法让我装饰装饰器,以便 Click 正确解析参数?

【问题讨论】:

  • 装饰器需要应用于裸函数。所以你不能轻易堆叠你的自定义装饰器。
  • 因此,从我在另一个线程中读到的内容来看,如果我能找到更新@click.option 使用的正确vars 的方法应该是可能的。据我所见,@click.option 在其包装的函数的__dict__ 中添加了一个新的__click_params__ 条目。我想我只需要确保我的装饰器传播它。

标签: python python-decorators python-click


【解决方案1】:

这是在我们的代码库中如何工作的示例(使用 click 7.1.2)。

def decorator_example(f):

    @pass_context
    @click.option("--testy")
    def wrapper(ctx, *args, testy, **kwargs):
        # Do stuff with testy here
        testy = f"pre{testy}"
    
    # Think this is the bit that allows click to be aware of options defined on the wrapper
    return ctx.invoke(wrapped_function, *args, testy=testy, **kwargs)

# Using functools to update the wrapper as required - think this is the same as @wraps(f)?
return update_wrapper(wrapper, wrapped_function)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-16
    • 2013-08-07
    • 2014-01-23
    • 2021-05-20
    • 2020-02-10
    • 2012-01-09
    相关资源
    最近更新 更多