Search code examples
pythoncommand-line-interfacepython-click

How to use same options for cmd in the same group by using python-click


I have code like below, both foo and bar have a user option and I need to write:

@click.option('--user', default='*')

twice for each function.

But I actually have a lot of cmds like this, so it is a lot of repeated code.

@click.group(help="cmd group")
def main():
    pass


@click.command(name='foo')
@click.option('--user', default='*')
def foo(user):
    click.secho(user, fg='green')


@click.command(name='bar')
@click.option('--user', default='*')
def bar(user):
    click.secho(user, fg='green')


main.add_command(foo)
main.add_command(bar)

What I want is to add the same option to one place in the group of cmd. ow can I do this using click?


Solution

  • pass it in the context:

    @click.group(help="cmd group")
    @click.option('--user', default='*')
    @click.pass_context
    def main(ctx, user):
        ctx.obj = {'user': user}
    
    
    @click.command(name='foo')
    @click.pass_context
    def foo(ctx):
        click.secho(ctx.obj['user'], fg='green')
    
    
    @click.command(name='bar')
    @click.pass_context
    def bar(ctx):
        click.secho(ctx.obj['user'], fg='green')
    
    
    main.add_command(foo)
    main.add_command(bar)
    

    mycli --user cats bar will echo cats from the bar subcommand