multiple optional positional arguments

451 views
Skip to first unread message

Thomas Moschny

unread,
Jan 5, 2011, 11:32:57 AM1/5/11
to argparse-users
Is it possible to specify a parser for this commandline: "command
[[foo] bar]"?

The idea is that the command can be called with zero, one, or two
arguments, and if called with one arg that arg should be assigned to
bar, not to foo. Maybe what I'm looking for is sort of a non-greedy
optional positional arg, a-la nargs="??".

akira

unread,
Jan 7, 2011, 8:54:00 AM1/7/11
to argpars...@googlegroups.com
It seems equivalent to "command [bar] [foo]"

>>> import argparse
>>> p = argparse.ArgumentParser(prog='PROG')
>>> p.add_argument('bar', nargs='?')
>>> p.add_argument('foo', nargs='?')
>>> p.parse_args([]) # zero
Namespace(bar=None, foo=None)
>>> p.parse_args(['1']) # one
Namespace(bar='1', foo=None)
>>> p.parse_args(['1', '2']) # two
Namespace(bar='1', foo='2')
>>> p.print_usage()
usage: PROG [-h] [bar] [foo]


Thomas Moschny

unread,
Jan 7, 2011, 10:41:17 AM1/7/11
to argpars...@googlegroups.com
2011/1/7 akira <4kir...@gmail.com>:

> On 01/05/2011 07:32 PM, Thomas Moschny wrote:
>>
>> Is it possible to specify a parser for this commandline: "command
>> [[foo] bar]"?
>>
>> The idea is that the command can be called with zero, one, or two
>> arguments, and if called with one arg that arg should be assigned to
>> bar, not to foo. Maybe what I'm looking for is sort of a non-greedy
>> optional positional arg, a-la nargs="??".
>>
> It seems equivalent to "command [bar] [foo]"

Sure, but that wasn't the question. The ordering of foo and bar in my
case is important (and btw, it is equivalent to "command [bar
[foo]]").

Steven Bethard

unread,
Jan 7, 2011, 11:28:52 AM1/7/11
to argpars...@googlegroups.com

No, there's currently no way of getting this behavior. Your best bet
is probably to specify nargs='?' twice, and then do some post-hoc
processing to decide which is which, e.g.:

if args.bar is None:
args.bar = args.foo
args.foo = None

Steve
--
Where did you get that preposterous hypothesis?
Did Steve tell you that?
        --- The Hiphopopotamus

Reply all
Reply to author
Forward
0 new messages