0

Here's what I have that does not behave as I'd like it to:

import click

xmin_chlist = ['clauset', 'manual', 'percentile']


@click.command()
@click.option('-x', '--xmin', default=('clauset', None),
              type=(click.Choice(xmin_chlist), float),
              help=f'CHOICE one of {xmin_chlist}')
def get_uis(xmin):
    print(xmin)


if __name__ == '__main__':
    get_uis()

The above code is written toui.py, and invoking $ python ui.py on the command line without specifying the --xmin option prints the default ('clauset', None) as expected; so does providing 2 values to --xmin, such as $ python ui.py --xmin percentile 99.

But I'd also like to only be able to provide a single value to --xmin, such as $ python ui.py --xmin clauset and still get None as the default to the second value in the tuple, but instead I get the error Error: --xmin option requires 2 arguments. Furthermore, if possible I'd also like to be able to provide different second element defaults to 'manual' and 'percentile', when they are passed alone to --xmin instead of just the None for 'clauset'.

I tried using a callback to provide defaults based on the number of values passed to --xmin, but that does not appear to work either as the error prevents the callback from firing.

I understand that there is no built-in option type in Click which allows passing a variable number of values. So should I be creating my custom variable type? Or something else? What would be the best approach here?

Jethro Cao
  • 641
  • 1
  • 5
  • 12
  • 1
    So if I read your description correctly, you don't really want a "variable" number of values, but instead want to leave off elements at the end of a fixed length list of values and have the left off values just use default values? – Stephen Rauch Feb 22 '20 at 03:03
  • @StephenRauch Yes, I believe that should also allow me achieve what I'd want. My original thinking with having an `Option` instance accept variable number of values is because both of the non-clauset `xmin` choices (namely manual and percentile) require an additional float input to work; and ideally, I'd also like for these two options to have their own defaults for this additional float value. Lastly, there is also a 4th `xmin` choices yet to be implemented which would actually require 2 additional float inputs to work. So overall, I think it'd be cleaner to allow variable # inputs. – Jethro Cao Feb 22 '20 at 08:09
  • 1
    @StephenRauch actually, this solution of yours (https://stackoverflow.com/a/48394004/5437918) does pretty much what I want, so thanks :) – Jethro Cao Mar 04 '20 at 13:32

0 Answers0