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

paul j3 report at bugs.python.org
Tue May 7 00:51:33 CEST 2013


paul j3 added the comment:

This is the formal patch corresponding to the `test_intermixed.py`.  It includes changes to `argparse.rst`, plus tests in `test_argparse.py`.  These tests are near the end, after those for `parse_known_args`.  They are roughly equivalent to the examples in `test_intermixed.py`.
 -----------------
The new documentation section is:

Some users expect to freely intermix optional and positional argument strings. For example, optparse, by default, allows interspersed argument strings. GNU getopt() permutes the argument strings so non-options are at the end. The parse_intermixed_args() method emulates this behavior by first calling parse_known_args() with just the optional arguments being active. It is then called a second time to parse the list of remaining argument strings using the positional arguments.

parse_intermixed_args() raises an error if the parser uses features that are incompatible with this two step parsing. These include subparsers, argparse.REMAINDER, and mutually exclusive groups that include both optionals and positionals.

In this example, parse_known_args() returns an unparsed list of arguments [‘2’, ‘3’], while parse_intermixed_args() returns rest=[1, 2, 3].

    >>> parser = argparse.ArgumentParser()
    >>> parser.add_argument('--foo')
    >>> parser.add_argument('cmd')
    >>> parser.add_argument('rest', nargs='*', type=int)
    >>> parser.parse_known_args('cmd1 1 --foo bar 2 3'.split())
    (Namespace(cmd='cmd1', foo='bar', rest=[1]), ['2', '3']) 
    >>> parser.parse_intermixed_args('cmd1 1 --foo bar 2 3'.split())
    Namespace(cmd='cmd1', foo='bar', rest=[1, 2, 3])

parse_known_intermixed_args() method, returns a two item tuple containing the populated namespace and the list of remaining argument strings. parse_intermixed_args() raises an error if there are any remaining unparsed argument strings.

----------
Added file: http://bugs.python.org/file30160/intermixed.patch

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


More information about the docs mailing list