diff options
author | slateny <46876382+slateny@users.noreply.github.com> | 2022-05-13 14:17:07 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-05-13 14:17:07 (GMT) |
commit | 3e3e8976b8096ae1c52432bd3be15784ea82d956 (patch) | |
tree | 63ac25c5bb2d8abb67be647465801e53a9568e0d | |
parent | 57da3ff586c66a8d08abbee37736b9fb6f0b7112 (diff) | |
download | cpython-3e3e8976b8096ae1c52432bd3be15784ea82d956.zip cpython-3e3e8976b8096ae1c52432bd3be15784ea82d956.tar.gz cpython-3e3e8976b8096ae1c52432bd3be15784ea82d956.tar.bz2 |
bpo-9182: Add a section on specifying positional arguments (#31810)
-rw-r--r-- | Doc/howto/argparse.rst | 29 | ||||
-rw-r--r-- | Doc/library/argparse.rst | 7 |
2 files changed, 34 insertions, 2 deletions
diff --git a/Doc/howto/argparse.rst b/Doc/howto/argparse.rst index a97d10c..3075b01 100644 --- a/Doc/howto/argparse.rst +++ b/Doc/howto/argparse.rst @@ -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 ------------------- diff --git a/Doc/library/argparse.rst b/Doc/library/argparse.rst index 1f40e4a..83dd3cdf 100644 --- a/Doc/library/argparse.rst +++ b/Doc/library/argparse.rst @@ -951,8 +951,8 @@ nargs ArgumentParser objects usually associate a single command-line argument with a single action to be taken. The ``nargs`` keyword argument associates a -different number of command-line arguments with a single action. The supported -values are: +different number of command-line arguments with a single action. +See also :ref:`specifying-ambiguous-arguments`. The supported values are: * ``N`` (an integer). ``N`` arguments from the command line will be gathered together into a list. For example:: @@ -1610,6 +1610,9 @@ argument:: >>> parser.parse_args(['--', '-f']) Namespace(foo='-f', one=None) +See also :ref:`the argparse howto on ambiguous arguments <specifying-ambiguous-arguments>` +for more details. + .. _prefix-matching: Argument abbreviations (prefix matching) |