Author paul.j3
Recipients bethard, chris.jerdonek, gfxmonk, martin.panter, paul.j3, tshepang, waltermundt
Date 2013-08-25.02:11:57
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1377396718.05.0.0919602988642.issue15112@psf.upfronthosting.co.za>
In-reply-to
Content
I originally posted this on http://bugs.python.org/issue14191, but I think it belongs here.  The patch I proposed is similar to berthard's, popping items off the end of 'args_counts'.  I intend to check whether the logic is equivalent.

----------------------------
copy from http://bugs.python.org/msg187051
----------------------------
This patch permits the mixing of optionals with positionals, with the caveat that a particular positional cannot be split up.

If:

    parser = ArgumentParser()
    parser.add_argument('-f','--foo')
    parser.add_argument('cmd')
    parser.add_argument('rest', nargs='*')

    '-f1 cmd 1 2 3', 
    'cmd -f1 1 2 3', 
    'cmd 1 2 3 -f1' 

all give {cmd='cmd', rest=['1','2','3'], foo='1'}.  

But 'cmd 1 -f1 2 3', does not recognize ['2','3'].

Previously 'cmd -f1 1 2 3' would return rest=[], and not recognize ['1','2','3'].  With this change the nargs='*' behaves more like nargs='+', surviving to parse the 2nd group of positional strings.

The trick is to modify arg_counts in consume_positionals(), removing matches that don't do anything (don't consume argument strings). 

    if 'O' in arg_strings_pattern[start_index:]:
        # if there is an optional after this, remove
        # 'empty' positionals from the current match
        while len(arg_counts)>1 and arg_counts[-1]==0:
            arg_counts = arg_counts[:-1]

This change passes all of the existing test_argparse.py tests.  It also passes the optparse tests that I added in http://bugs.python.org/issue9334#msg184987
I added 4 cases to illustrate this change.
History
Date User Action Args
2013-08-25 02:11:58paul.j3setrecipients: + paul.j3, bethard, gfxmonk, chris.jerdonek, tshepang, martin.panter, waltermundt
2013-08-25 02:11:58paul.j3setmessageid: <1377396718.05.0.0919602988642.issue15112@psf.upfronthosting.co.za>
2013-08-25 02:11:58paul.j3linkissue15112 messages
2013-08-25 02:11:57paul.j3create