[docs] [issue14191] argparse doesn't allow optionals within positionals

paul j3 report at bugs.python.org
Fri Mar 29 21:56:14 CET 2013

paul j3 added the comment:

I looked at your t18a.py test case

    parser = ArgumentParser()
    parser.add_argument('--foo', dest='foo')
    parser.add_argument('--bar', dest='bar')
    parser.add_argument('baz', nargs='*')

and parse variations on 'a b c d --foo x --bar 1'

I think your main problem is with the 'baz', nargs='*'.  If nargs was changed to '+', 'a --foo x b c d --bar 1' would work, returning {foz='a', bar=['b','c','d']}.

argparse alternates between consuming positional and optionals until it runs out of arguments or argument strings.  But with '*', both 'foz' and 'baz' are consumed with the first set of positional strings {foz='a', baz=[]}.  When it gets to 'b c d' there are no more positional arguments to consume, so they get put into 'extras'.

With nargs='+', 'a b --foo x c d --bar 1' would assign {foz='a', baz=[b]}, and extras=['c','d'].

So while optionals can be interspersed with positionals, they can't be placed within the set of strings intended for one positional. That seems to me to very reasonable (why break up 'b c d'?).  And as your file demonstrates, you can fall back on parse_known_args to handle the extras.

nosy: +paul.j3

Python tracker <report at bugs.python.org>

More information about the docs mailing list