Ram Rachum Ram Rachum - 1 year ago 72
Python Question

Using the click package: Making an option be a choice of `int`

I'm trying to make a

click.option
be a choice between the numbers
0
,
1
and
2
. I tried this:

@click.Option('--verbosity', default=1, type=click.Choice([0, 1, 2]))
def f():
# ...
pass


But I get the exception
TypeError: sequence item 0: expected str instance, int found
. I guess
click
expects only strings in
click.Choice
. Any way to get it to accept ints? I know I can convert to int manually after it's received, but if there's an idiomatic way to receive an
int
choice, that'll be better.

Answer Source

You can use IntRange(min=0, max=2):

class click.IntRange(min=None, max=None, clamp=False)

A parameter that works similar to click.INT but restricts the value to fit into a range. The default behavior is to fail if the value falls outside the range, but it can also be silently clamped between the two edges.

From the docs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download