Search code examples
pythonpython-click

How to supply multiple options with array validation?


Given I have code like this:

columns = ['col1', 'col2', 'col3', 'col4']

@click.option('--columns', is_flag=False, 
  default=columns, show_default=True, metavar='<columns>', type=click.Choice(columns), 
  help='Sets target columns', multiple=True)

Then I can call my app like this:

./myapp --columns=col1

However, how to make this work with multiple items separated by comma, like so:

./myapp --columns=col1,col3

My goal is to retrieve the passed values from an resulting columns array ['col1', 'col3'].

I do NOT want to pass the option multiple times.


Solution

  • The multiple keyword in click.option is so you can pass the same option multiple times, e.g. --columns=col1 --columns=col2. Instead you can accept a string for columns and then extract and validate the columns yourself:

    cols = ['col1', 'col2', 'col3', 'col4']
    
    @click.option('--columns', is_flag=False, default=','.join(cols), show_default=True,
                  metavar='<columns>', type=click.STRING, help='Sets target columns')
    @click.command()
    def main(columns):
        # split columns by ',' and remove whitespace
        columns = [c.strip() for c in columns.split(',')]
    
        # validate passed columns
        for c in columns:
            if c not in cols:
                raise click.BadOptionUsage("%s is not an available column." % c)
    
        print(columns)