[New-bugs-announce] [issue16807] argparse group nesting lost on inheritance

Dougal Sutherland report at bugs.python.org
Sat Dec 29 02:39:27 CET 2012


New submission from Dougal Sutherland:

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.

----------
components: Library (Lib)
files: argparse_mutex_parent.patch
keywords: patch
messages: 178459
nosy: Dougal.Sutherland, bethard
priority: normal
severity: normal
status: open
title: argparse group nesting lost on inheritance
type: behavior
versions: Python 2.7, Python 3.2, Python 3.3, Python 3.4
Added file: http://bugs.python.org/file28473/argparse_mutex_parent.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue16807>
_______________________________________


More information about the New-bugs-announce mailing list