Search code examples
pythonpython-click

how to set default for multi value options


I want something like this:

import click

@click.command()
@click.option("-r", "--range", nargs=2, type=int, default=(1,2), show_default=True)
def scale(range):
   print "scale to %d - %d" % range

if __name__ == '__main__':
   scale()

But the default value for the option of multi values doesn't work here. How to do it correctly?


Solution

  • This is now implemented in master and will be generally available when v3 is released. It will work as you've written, by passing an iterable to default=. nargs= and multiple=True are supported, individually and together.

    @click.command()
    @click.option('--foo', default=[23, 42], type=click.FLOAT, multiple=True)
    def cli(foo):
        for item in foo:
            click.echo(item)
    
    @click.command()
    @click.option('--arg', default=((1, 2), (3, 4)), nargs=2, multiple=True, type=click.INT)
    def cli(arg):
        for item in arg:
            click.echo('<%d|%d>' % item)