typeshed
typeshed copied to clipboard
argparse type=bool
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.
We could now use @deprecated.
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)