问题
I have two Python CLI tools which share a set of common click.options. At the moment, the common options are duplicated:
@click.command()
@click.option('--foo', is_flag=True)
@click.option('--bar', is_flag=True)
@click.option('--unique-flag-1', is_flag=True)
def command_one():
pass
@click.command()
@click.option('--foo', is_flag=True)
@click.option('--bar', is_flag=True)
@click.option('--unique-flag-2', is_flag=True)
def command_two():
pass
Is it possible to extract the common options in to a single decorator that can be applied to each function?
回答1:
You can build your own decorator that encapsulates the common options:
def common_options(function):
function = click.option('--unique-flag-1', is_flag=True)(function)
function = click.option('--bar', is_flag=True)(function)
function = click.option('--foo', is_flag=True)(function)
return function
@click.command()
@common_options
def command():
pass
来源:https://stackoverflow.com/questions/50061342/is-it-possible-to-reuse-python-click-option-decorators-for-multiple-commands