argparse icon indicating copy to clipboard operation
argparse copied to clipboard

[BUG] Flag-like parameters do not store implicit values for `nargs(0, 1)`

Open Jacobfaib opened this issue 8 months ago • 0 comments

bool value = false;

parser.add_argument("--foo").store_into(value).nargs(0, 1);
parser.parse_args({"prog", "--foo"});

assert(value); // fails

This pattern is useful if you want to support "rich" boolean flags:

--flag   // flag is true
--flag 0 // flag is false
--flag 1 // flag is true
// ..etc. 

It seems like the bug is in Argument::consume():

if (num_args_max == 0) {
  if (!dry_run) {
    m_values.emplace_back(m_implicit_value);
    ...
    return start;
  }
}

Here num_args_max == 1, but the else branch does not do m_values.emplace_back(m_implicit_value) when it finds there are no more arguments. The same bug also happens when

parser.parse_args({"prog", "--foo", "--some-other-arg", "value"});

foo is not filled with the implicit value.

Jacobfaib avatar Apr 18 '25 23:04 Jacobfaib