[issue9338] argparse optionals with nargs='?', '*' or '+' can't be followed by positionals
paul j3
report at bugs.python.org
Tue May 14 06:29:00 CEST 2013
paul j3 added the comment:
I've played a bit the idea that barthard sketched. I don't have all the details worked out, but I believe this is what will happen:
With
parser = argparse.ArgumentParser()
parser.add_argument('-w')
parser.add_argument('-x', nargs='+')
parser.add_argument('y')
parser.add_argument('z', nargs='*')
some possible parses are
'-w 1 -x 2 3 4 5', # w:1, x:[2,3,4], y:5, z:[] -
# fail +
'-w 1 2 -x 3 4 5', # w:1, y:2, x:[3 4 5], z:[] +
'-w 1 -x 2 3', # w:1, x:[2], y:3, z:[] -
# fail +
'-x 1 2 -w 3 4 5 6', # w:3, x:[1,2], y:4, z:[5,6] +
# w:3, x:[1], y:2, z:[4,5,6] -
'-x 1 2 3 4 -w 5 6 7', # w:5, x:[1,2,3,4], y:5, z:[7] +
# w:5, x:[1,2,3], y:4, z:[6,7] -
'1 2 3 -x 4 5 -w 6', # w:6, x:[4,5], y:1, z:[2,3] +
'+' lines are those currently produced
'-' lines are ones that would be produced by these ideas
'-w 1 -x 2 3 4 5' is the protypical problem case. The current parser allocates all [2,3,4,5] to -x, leaving none for y, thus failing. So desired solution is to give 5 to y, leaving -x with the rest.
'-x 1 2 -w 3 4 5 6' is a potentially ambiguous case. The current parser lets -x grab [1,2]; y then gets 4, and z the remainder. But the alternative is to give 2 to y, leaving -x with just [1].
In this case
arg_strings_pattern = 'OAAOAAAA'
replacing the Os with the option flags: '-xAA-wAAAA'
I match this with a refined version of bethard's regex:
pat1='((?:-wA)|(?:-xA+)|(?:-wA-xA+)|(?:-xA+-wA))'
pat = _re.compile('%s?(?P<y>A)%s?(?P<z>A*)%s?'%(pat1,pat1,pat1))
groups (without the Nones) and groupdict are
['-xA', 'A', '-wA', 'AAA']
{'z': 'AAA', 'y': 'A'}
So this does effectively give y the 2nd argument, leaving -x with just the 1st.
The current parser effectively groups the arguments as
['-xAA, '-wA', 'A', 'AA']
In the real world, generating and apply a global pattern like this could get complicated. For example there are long option names ('--water'), and combined argument strings ('-x1', '-x=1').
----------
_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue9338>
_______________________________________
More information about the Python-bugs-list
mailing list