◐ Shell
clean mode source ↗

bpo-9182: Add a section on specifying positional arguments by slateny · Pull Request #31810 · python/cpython

Expand Up @@ -664,6 +664,35 @@ Output: 4^2 == 16

.. _specifying-ambiguous-arguments:
Specifying ambiguous arguments ------------------------------
When there is ambiguity in deciding whether an argument is positional or for an argument, ``--`` can be used to tell :meth:`~ArgumentParser.parse_args` that everything after that is a positional argument::
>>> parser = argparse.ArgumentParser(prog='PROG') >>> parser.add_argument('-n', nargs='+') >>> parser.add_argument('args', nargs='*')
>>> # ambiguous, so parse_args assumes it's an option >>> parser.parse_args(['-f']) usage: PROG [-h] [-n N [N ...]] [args ...] PROG: error: unrecognized arguments: -f
>>> parser.parse_args(['--', '-f']) Namespace(args=['-f'], n=None)
>>> # ambiguous, so the -n option greedily accepts arguments >>> parser.parse_args(['-n', '1', '2', '3']) Namespace(args=[], n=['1', '2', '3'])
>>> parser.parse_args(['-n', '1', '--', '2', '3']) Namespace(args=['2', '3'], n=['1'])

Conflicting options -------------------
Expand Down