0

Let's suppose that we have already defined argument groups. Now I want to get access to one of them in order to add some extra argument. So what is the best way to do this in argparse? Now my approach looks like as follows:

def get_parser(self, ...):
    parser = ...

    matching_groups = (g for g in parser._action_groups
                       if g.title == 'group name')
    group = next(matching_groups, None) or parser
    group.add_argument('-s', '--some-new-argument', ...)
    return parser

Is there any more elegant way that allows do not access 'protected' members directly?

wim
  • 338,267
  • 99
  • 616
  • 750
machin
  • 440
  • 8
  • 21
  • No, there isn't any 'non-protected' list of these groups. In Python the use of attribute names like this means "we don't expect casual users to need these", but knowledgeable users aren't prohibited from using them. In `argparse.py`, `_action_groups` is used with the `parents` mechanism in `_add_container_actions`, and when setting up the `help formatter`. The list isn't used in parsing. – hpaulj Nov 18 '17 at 20:04
  • Other uses of `_action_groups`: https://stackoverflow.com/questions/39047075/reorder-python-argparse-argument-groups, https://stackoverflow.com/questions/12268602/sort-argparse-help-alphabetically. – hpaulj Nov 18 '17 at 20:09

0 Answers0