argparse icon indicating copy to clipboard operation
argparse copied to clipboard

Arguments following another argument with explicit .choices() will incorrectly inherit the choices

Open tlemo opened this issue 1 year ago • 6 comments

  args.add_argument("--foo");
  args.add_argument("--bar").choices("a", "b", "c");

With the latest version, passing foo before bar works as expected:

test --foo=x --bar=a

But if foo is passed after bar it's incorrectly rejected:

test --bar=a --foo=x

Invalid argument "--foo" - allowed options: {a, b, c}"

tlemo avatar Jul 17 '24 21:07 tlemo

This was fixed here. I'll make a new release soon (long overdue). In the meantime, can you check with the latest commit in the main branch?

p-ranav avatar Jul 17 '24 23:07 p-ranav

Created a new release: https://github.com/p-ranav/argparse/releases/tag/v3.1

p-ranav avatar Jul 17 '24 23:07 p-ranav

@p-ranav I still see this issue with 3.1 version

mikisch81 avatar Aug 05 '24 14:08 mikisch81

@p-ranav Ok to be more specific the issue happens when I set --bar to accept variable length of arguments:

  argparse::ArgumentParser args("arg_test");
  args.add_argument("--foo");
  args.add_argument("--bar")
      .nargs(1, 3)
      .choices("a", "b", "c");

So if I give all 3 choices it works ok, but if I give 1 or 2, then it fails:

> ./arg_test --bar a b c --foo x
>
> ./arg_test --bar a b --foo x
Invalid argument "--foo" - allowed options: {a, b, c}
Usage: arg_test [--help] [--version] [--foo VAR] [--bar VAR...]

Optional arguments:
  -h, --help     shows help message and exits
  -v, --version  prints version information and exits
  --foo
  --bar          [nargs=1..3]
>

mikisch81 avatar Aug 06 '24 08:08 mikisch81

Hi @p-ranav @mikisch81, Regarding variable length list of arguments:

program.add_argument("--input_files")
  .nargs(1, 3);  // This accepts 1 to 3 arguments.
  • It's not handled successfully.
  • If you checked this condition, you will notice that the tester needs to pass max number of expected arguments.
  • Fix needed.

Eng-MohamedHussien avatar Aug 17 '24 16:08 Eng-MohamedHussien

  • I already prepared the fix locally, but by the end of the next weekend I will prepare the pull request.

Eng-MohamedHussien avatar Aug 17 '24 16:08 Eng-MohamedHussien