I\'d like to parse a command line that has a mutually exclusive group of options. Normally, I\'d just use --foo bar
which would produce, in the namespace, ar
Subclassing Action
is exactly what the developers expect you to do. Even the default, most common action, 'store' is a subclass, argparse._StoreAction
. argparse._StoreTrueAction
is a subclass of argparse._StoreConstAction
, differing only in the default
and const
defaults.
To deal with the missing attribute case you could initialize them in a couple of ways:
set_defaults
lets you define any defaults, regardless of whether any arguments use them or not. In the documentation that is used to add function objects to the namespace when using subparsers.
parser.set_defaults(thing_key=None, thing=None)
You could also create a namespace with the defaults, and pass that as an
argument to parse_args
.
myNamespace = argparse.Namespace(thing_key=None, thing=None)
parser.parse_args(names=myNamespace)
If you don't want a foo=None
default in the namespace, define its default as argparse.SUPPRESS
.