Message178459
If you wrap a mutually exclusive group inside an argument group in an argparse.ArgumentParser, and then use parents= to inherit from that parser, the non-exclusive argument group is forgotten in the help output, and the arguments move to the default "optional arguments" section. For example:
# construct the parser with a mutually exclusive group
>>> import argparse
>>> parent = argparse.ArgumentParser(add_help=False)
>>> group = parent.add_argument_group('the group')
>>> group.add_argument('--foo') and None
>>> mutex = group.add_mutually_exclusive_group()
>>> mutex.add_argument('-a', action='store_true') and None
>>> mutex.add_argument('-b', action='store_true') and None
>>> parent.print_help()
usage: [--foo FOO] [-a | -b]
the group:
--foo FOO
-a
-b
# now try to inherit from it; "the group" is forgotten for
# mutex arguments, but remains for others
>>> argparse.ArgumentParser(add_help=False, parents=[parent]).print_help()
usage: [--foo FOO] [-a | -b]
optional arguments:
-a
-b
the group:
--foo FOO
I see the same behavior on 2.7.3 and 3.3.0.
The problem is that [`argparse._ActionsContainer._add_container_actions`](http://hg.python.org/releasing/2.7.3/file/7bb96963d067/Lib/argparse.py#l1331) always adds mutex groups to the top level, rather than to the equivalent of their `_container` attribute. The attached patch fixes this, and adds a test based on the formatted output (almost identical to the `test_groups_parents` test).
One thing about the patch: it assumes that the `_container` attribute of all the mutex groups will be either the `container` argument to `_add_container_actions` or an argument group that has been processed in `group_map`. If this is not the case, it'll fail with either an `AttributeError` or a `KeyError`. I don't know when this would happen, or if it's common enough that it's worth checking for more explicitly. |
|
Date |
User |
Action |
Args |
2012-12-29 01:39:27 | dougalsutherland | set | recipients:
+ dougalsutherland, bethard |
2012-12-29 01:39:27 | dougalsutherland | set | messageid: <1356745167.13.0.671311915058.issue16807@psf.upfronthosting.co.za> |
2012-12-29 01:39:26 | dougalsutherland | link | issue16807 messages |
2012-12-29 01:39:25 | dougalsutherland | create | |
|