paul j3 <[email protected]> added the comment:
Just clarify how the code currently works. `subparsers` is a positional Action
of subclass _SubParsersAction. It has a nargs='+...', requiring at least one
string, and taking all remaining strings. Its __call__ has the standard
signature. So everything that's special about subparsers is embodied in this
Action subclass.
def __call__(self, parser, namespace, values, option_string=None):
parser_name = values[0]
arg_strings = values[1:]
# set the parser name if requested
if self.dest is not SUPPRESS:
setattr(namespace, self.dest, parser_name)
# select the parser
try:
parser = self._name_parser_map[parser_name]
...
So the `parser_name` is first string, the actual alias that user provided. It
is added to the namespace if a `dest` was provided (the default `dest` is
SUPPRESS). That's all of the relevant code - the alias is simply added to to
Namespace.
As mentioned before `parser_name` is used find the actual sub parser, which is
called with the remaining `arg_strings`.
Earlier in the subclasses `add_parser` method, the 'name' and 'alias' list are
used to populate the '_name_parser_map' mapping, and also create the metavar
that's used in the help display. But neither is saved as an attribute.
---
I still think 'set_defaults' is the cleanest way of saving a unique name for a
sub parser.
parser_foo.set_defaults(func=foo, name='foo')
---
One further note - if you make subparsers required, you should also set a dest
name:
parser.add_subparsers(dest='cmd', required=True)
otherwise the missing-subparsers error message will raise an error. It needs
to identify the missing action in some way. Functionally, this might be the
most important reason to set the 'dest'.
----------
_______________________________________
Python tracker <[email protected]>
<https://bugs.python.org/issue36664>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe:
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com