argparse icon indicating copy to clipboard operation
argparse copied to clipboard

raise_on_error doesn't work as expected.

Open asaff1 opened this issue 1 year ago • 1 comments

Hello, First, this is a nice library! very clean API.

Some suggestions for improvement:

  1. I would expect raise_on_error to throw when unrecognized argument is provided. (Similar to how python argparse behaves) Instead the library simply prints a message "unrecognized argument" and moves on. Also no flag is returned that the user can act a upon (maybe a subclass hook). This may lead to typos that the user won't notice.

  2. Can be nice if the library can accept both --my-value and --my_value (also done by Python argparse)

asaff1 avatar Jul 10 '24 07:07 asaff1

+1 - nifty library and super simple to use, but raise_on_error really should handle unrecognised arguments because it's so easy to misspell an argument and because the default 'print the error and exit the program' behaviour does not apply to unrecognised arguments so there is currently no way to handle them at all.

For my use case raising the error immediately on reaching an unknown argument is the desired behaviour, and you can do this by replacing this line:

cerr << "unrecognised commandline argument: " << key << endl;

with this

if (raise_on_error)
    throw std::runtime_error("unrecognised commandline argument :  " + key);
else
    cerr << "unrecognised commandline argument :  " << key << endl;

otherstew avatar Jan 23 '25 22:01 otherstew

Hi @asaff1 ,

I have now updated the behavior for raise_on_error as suggested by @sjmduncan , thanks for the suggestion!

As for the supporting both dash and underscore, you could add more than 2 aliases, e.g.

struct MyArgs2 : public argparse::Args {
    std::string &my_value = kwarg("my-value,my_value", "my value");
};

This will support both the my-value and my_value. If you want to add a short-alias as well you can just add more comma-separated values, e.g; "v,my-value,my_value"

morrisfranken avatar Mar 16 '25 21:03 morrisfranken