zenlotus / argparse

Automatically exported from code.google.com/p/argparse
Other
0 stars 0 forks source link

optional subparsers #47

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
parser = argparse.ArgumentParser()
sub = parser.add_subparsers()
sub.add_parser("info")
parser.add_argument("paths", "+")
parser.parse_args(["foo", "bar"])

What is the expected output? What do you see instead?
Expected behavior is that, failing to match one of the subparser inputs
("info"), the parser checks if the argument matches any of the top-level
arguments, in this case the 'paths' multi-arg. In other words, it should be
possible to make the subparser be optional, such that when the subparser
argument fails to retrieve any valid subparser, the remaining args are
parsed as if no subparser exists. At present, it does not seem possible to
make a subparser be optional at all.
Perhaps this could be exposed to the user as:
parser.add_subparsers(nargs=argparse.OPTIONAL)
or something to that effect. Or, allow a default subparser to be specified.
I.e.,

sub = parser.add_subparsers()
info = sub.add_parser("info")
main = sub.add_parser("main")
sub.default = main

I'm sure the point will come up that the current behavior is correct,
because given a subparser like "info", a user could easily make a mistake
like "myapp ino foo bar" and rather than get a safe error be given
something unexpected. For this reason, I think the default behavior is
usually going to be correct. BUT, it would still be nice if it could be
optional, so that developers could be free to make that call. Sometimes the
potential user errors aren't really an issue, and having to explicitly set
a subparse arg every time can be a nuissance.

Original issue reported on code.google.com by sgusta...@gmail.com on 28 Nov 2009 at 3:35

GoogleCodeExporter commented 9 years ago
I'm certainly open to such a feature. Patches are welcome. :)

To make this work we'd have to teach _SubParsersAction to accept nargs='?'. 
This is a
little complicated because currently _SubParsersAction tells the parser that it 
wants
to consume everything else by passing nargs=PARSER. So we'd need some sort of
nargs=PARSER_OR_NOTHING and the corresponding code everywhere that nargs is 
used.
Perhaps there's an easier way though...

Original comment by steven.b...@gmail.com on 7 Dec 2009 at 12:17

GoogleCodeExporter commented 9 years ago
I was just trying to set up optional subparsers and stumbled upon this thread. 
Has
there been any progress on this issue?

Regards, Lars

Original comment by swedishl...@gmail.com on 22 Apr 2010 at 5:12

GoogleCodeExporter commented 9 years ago
Nope. ;-)

Original comment by steven.b...@gmail.com on 22 Apr 2010 at 10:36

GoogleCodeExporter commented 9 years ago
Moved to http://bugs.python.org/issue9253

Original comment by steven.b...@gmail.com on 23 Jul 2010 at 12:03