[issue17218] support title and description in argparse add_mutually_exclusive_group
paul j3
report at bugs.python.org
Wed Apr 16 21:15:20 CEST 2014
paul j3 added the comment:
Using a mutually_exclusive_group is a little more complicated than I implied in the previous post.
p=argparse.ArgumentParser()
g=p.add_mutually_exclusive_group()
# currently the code objects to 'title' and 'description' keywords
g.add_argument('--foo')
g.add_argument('--bar')
# but a title can be added after creation
g.title='test'
g.description='description'
# now add the group to the list that is used for help formatting
p._action_groups.append(g)
p.print_help()
producing:
usage: ipython [-h] [--foo FOO | --bar BAR]
optional arguments:
-h, --help show this help message and exit
--foo FOO
--bar BAR
test:
description
--foo FOO
--bar BAR
Now the arguments appear in both the 'optional arguments' group (a default one), and the new group. That's not what we want.
So the mutually_exclusive_group has to be changed so it accepts title and description. And it also has to block the addition of arguments to one of the existing groups.
A key difference is in how _add_action is implemented for the 2 group classes:
For argument_group:
def _add_action(self, action):
action = super(_ArgumentGroup, self)._add_action(action)
self._group_actions.append(action)
return action
for mutually exclusive group
def _add_action(self, action):
...
action = self._container._add_action(action)
self._group_actions.append(action)
return action
The first uses 'super' to add the action to itself. The second adds the action to its 'container'.
That difference allows you to add a mutually_exclusive_group to an argument_group (or to another mutually_exclusive_group), but you can't add an argument_group to another argument_group (no nesting).
I don't like the idea of using a different _add_action method depending on whether group has a 'title' or not. That's too kludgy.
Another possibility is to have 'parser.add_mutually_exclusive_group()' do what I first demonstrated - first create an 'argument_group' with the title, and add the mutually_exclusive_group to that. This is still kludgy, but the change is limited to one function. For demonstration purposes it probably could be implemented in a new function (add_titled_mutually_exclusive_group).
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue17218>
_______________________________________
More information about the Python-bugs-list
mailing list