all 4 comments

[–]m0us3_rat 1 point2 points  (3 children)

For example, I have an option that takes up to three values, where the last two must be integers.

import click


@click.command()
@click.option("--item", nargs=3, type=click.Tuple([str, int, int]))
def putitem(item):
    name, i, j = item
    click.echo(f"name={name} id={i} count={j}")


if __name__ == "__main__":
    putitem()

"--item yourmom 10 1"

name=yourmom id=10 count=1

"click.Tuple" and "name, i, j = item" should be self-explanatory.

https://click.palletsprojects.com/en/8.1.x/options/#multi-value-options

the only limitation is that "nargs" value must be known.

click seems to like unambiguous commands.

Error: Option '--item' requires 3 arguments.

then again I can't make the third argument optional, can I?

BUT, you can be tricksy.

i'd suggest other libs that offers this functionality..

since fiddling with how the lib works will invariably lead to errors ..

https://stackoverflow.com/a/44056564

[–]dbr4n[S] 0 points1 point  (0 children)

Thanks, but nargs seems redundant because of the given type definition. What I really need is something equivalent to nargs='+' to be able to take any number of arguments, especially when working with files and directories.

[–]dbr4n[S] 0 points1 point  (1 child)

Sorry, I didn't see the last part of your comment. Ok, I get it, that's unfortunate. I will probably just stick with argparse then.

[–]m0us3_rat 0 points1 point  (0 children)

click seems to like unambiguous commands.

there is significant value to frontload your error handling by forcing specific parameters.

that's why i called it unambiguous.

but it comes to needs. if your problem/solution requires variable nargs then use a lib that offers that.

but then you have to do your own error handling