Is it possible to reuse python @click.option decorators for multiple commands? Is it possible to reuse python @click.option decorators for multiple commands? python python

Is it possible to reuse python @click.option decorators for multiple commands?


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_optionsdef command():    pass


Here is a decorator that uses the same principle from the previous answer:

def group_options(*options):    def wrapper(function):        for option in reversed(options):            function = option(function)        return function    return wrapperopt_1 = click.option("--example1")opt_2 = click.option("--example2")opt_3 = click.option("--example3")@cli.command()@click.option("--example0")@group_options(opt_1, opt_2, opt_3)def command(example0, example1, example2, example3):    pass


If you want to add parameters to such a function, you need to wrap it once more:

def common_options(mydefault=True):    def inner_func(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, default=mydefault)(function)        return function    return inner_func@click.command()@common_options(mydefault=False)def command():    pass