typeshed icon indicating copy to clipboard operation
typeshed copied to clipboard

argparse type=bool

Open Akuli opened this issue 3 years ago • 2 comments
trafficstars

When adding an argument with argparse.ArgumentParser.add_argument, it is tempting to pass type=bool to create an option that is specified without a value, such as --enable-foo. This doesn't work, and in fact creates a subtle bug: --enable-foo silently swallows the next argument, so a command like python3 program.py --enable-foo x y z will work but only leave y and z to be used as other arguments. https://stackoverflow.com/a/15008806

To prevent this, I think the best we can do is to add an overload that returns NoReturn when you pass in type=bool.

Akuli avatar Jan 04 '22 21:01 Akuli

We could now use @deprecated.

Akuli avatar Nov 18 '23 11:11 Akuli

We could now use @deprecated.

Which would also allow suggesting a replacement and customizing it per python-version.

That stackoverflow answer also has good alternatives if --arg=True/--arg=False is really what's wanted. (either ast.literal_eval, or a custom method)

My only hesitation is the "deprecation" semantic. Otherwise the decorator does everything we want about "warning" and teaching the user about code that is technically valid, but probably not what they wanted to do (which is pretty close to a linter's job huh)

Avasam avatar Nov 30 '23 00:11 Avasam