[issue11354] argparse: nargs could accept range of options count

paul j3 report at bugs.python.org
Fri May 10 01:29:08 CEST 2013


paul j3 added the comment:

This patch adds this `nargs='{m,n}'` or `nargs=(m,n)` feature.

It builds on the `better nargs error message` patch in http://bugs.python.org/msg187754

It includes an argparse.rst paragraph, changes to argparse.py, and additions to test_argparse.py.

The tests include those proposed by wm, rewritten to use the ParserTestCase framework where possible.  I did not give a lot of thought to test names.  The coverage could also use further thought.

As WM noted some range cases are the equivalent to existing nargs options ('{1,}'=='+').  I did not attempt to code or test such equivalences.  Since the '{0,}' form uses regex matching just like '*',
I don't think there is any advantage to making such a translation.  

I convert the tuple version (m,n) to the re string '{m,n}' during the add_argument() testing.  So it is the string form that is added to the parser action.  This is also the format that appears in usage.

The documentation paragraph is:

'{m,n}'. m to n command-line arguments are gathered into a list. This is modeled on the Regular Expression use. '{,n}' gathers up to n arguments. '{m,}' gathers m or more. Thus '{1,}' is the equivalent to '+', and '{,1}' to '?'. A tuple notation is also accepted, '(m,n)', '(None,n)', '(m,None)'. For example:

    >>> parser = argparse.ArgumentParser(prog='PROG')
    >>> parser.add_argument('--foo', nargs='{2,4}')
    >>> parser.parse_args('--foo a b c'.split())
    Namespace(foo=['a', 'b', 'c'])
    >>> parser.parse_args('--foo a'.split())
    usage: PROG [-h] [--foo FOO{2,4}]
    PROG: error: argument --foo: expected {2,4} arguments

----------
Added file: http://bugs.python.org/file30187/nargsrange.patch

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue11354>
_______________________________________


More information about the Python-bugs-list mailing list