Join GitHub today
GitHub is home to over 28 million developers working together to host and review code, manage projects, and build software together.Sign up
bpo-8538: Add support for boolean actions to argparse #11478
Hello, and thanks for your contribution!
I'm a bot set up to make sure that the project can legally accept your contribution by verifying you have signed the PSF contributor agreement (CLA).
Unfortunately we couldn't find an account corresponding to your GitHub username on bugs.python.org (b.p.o) to verify you have signed the CLA (this might be simply due to a missing "GitHub Name" entry in your b.p.o account settings). This is necessary for legal reasons before we can look at your contribution. Please follow the steps outlined in the CPython devguide to rectify this issue.
You can check yourself to see if the CLA has been received.
Thanks again for your contribution, we look forward to reviewing it!
I was about to write a patch to add the same feature. Good thing that I decided to look if someone was already working on it, thank you :-)
I'd like to contribute with the following comments:
1. Register action rather than exposing the class
I don't think
self.register('action', 'optional_boolean', _BooleanOptionalAction)
2. Be aware of short options
Your current implementation does not ignore short options when adding the prefix
3. Ordering of parameters names
I think the
parser.add_argument('--foo', '--bar', action='optional_boolean', ...)
Then, in the help message,
In the case of registering the action 'optional_boolean', it would be necessary to update the documentation on the list of supported values for the
5. My custom action class
About (2) and (3), I have a custom implementation in one project of mine that does that:
class BoolAction(argparse.Action): def __init__(self, option_strings, dest, **kw): self.original_option_strings = option_strings kw['nargs'] = 0 option_strings =  for s in self.original_option_strings: option_strings.append(s) if s.startswith('--'): s = '--no-' + s[2:] option_strings.append(s) super(BoolAction, self).__init__(option_strings, dest, **kw) def __call__(self, parser, namespace, values, option_string): value = option_string in self.original_option_strings setattr(namespace, self.dest, value)