[issue19462] Add remove_argument() method to argparse.ArgumentParser

paul j3 report at bugs.python.org
Fri Nov 1 08:36:00 CET 2013


paul j3 added the comment:

When you add an argument, argparse creates an `Action`, and returns it.  It also places that action in various lists (e.g. parse._actions) and dictionaries.  A `remove_argument` function would have to trace and remove all of those links.  That's a non-trivial task.  However modifying an argument (or Action) is much easier, since there is only one instance.  Obviously some modifications will be safer than others.

For example:

    parser = ArgumentParser()
    a = parser.add_argument('--foo')
    print a

produces:

    _StoreAction(option_strings=['--foo'], dest='foo', nargs=None,    const=None, default=None, type=None, choices=None, help=None, metavar=None)

`vars(a)` gives a somewhat longer list of attributes.  Within reason, those attributes can be changed directly.  I think the 'dest', 'help', 'nargs', 'metavar' could all be changed without hidden effects.  There's also a 'required' attribute that could be changed for optionals.  Changing the 'option_strings' might be problematic, since the parser has a dictionary using those strings as keys.

The constant `argparse.SUPPRESS` is used in several places to alter actions.  For example, to suppress the help, or to suppress default values in the Namespace.  So it might be possible to 'hide' arguments in the subclass, even if you can't remove them.

In http://bugs.python.org/issue14191 I explored a couple of ways of temporarily 'deactivating' certain groups of arguments, so as to parse the optionals and positionals separately.  It's an advance issue, but might still give some ideas. 

Another possibility is to use 'parent' parsers to define clusters of arguments.  Your base class could create a parser with one set of parents, and the subclass could use a different set.

----------
nosy: +paul.j3

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


More information about the Python-bugs-list mailing list