Sub topic 7
Multiple values, defaults and required options
This chapter assumes you can create a parser, add positional arguments and options, and call parse_args. Here you will control how many values an argument takes, what it holds when the user leaves it out, and when leaving it out is an error.
Controlling how many values an argument takes
The nargs parameter of add_argument sets how many command-line strings one argument consumes. Without it, an argument takes exactly one value, and the result is a single value rather than a list.
| `nargs` | Meaning | Result when present |
|---|---|---|
| omitted | exactly one value | the value itself |
| `3` (any integer) | exactly that many values | list of that length |
| `"?"` | zero or one value | the value, or `const` if given with no value |
| `"*"` | zero or more values | list, possibly empty |
| `"+"` | one or more values | list with at least one item |
Any nargs other than "?" produces a list, even nargs=1, which gives a one-item list. Each item is converted with type, so type=float with nargs=2 yields two floats.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("files", nargs="+", help="one or more input files")
parser.add_argument("--point", nargs=2, type=float, metavar=("X", "Y"))
parser.add_argument("--tag", nargs="*", default=[])
parser.add_argument("--out", nargs="?", const="out.txt", default=None)
args = parser.parse_args(
["a.txt", "b.txt", "--point", "1", "2.5", "--tag", "x", "y", "--out"]
)
print(args.files, args.point, args.tag, args.out)This prints ['a.txt', 'b.txt'] [1.0, 2.5] ['x', 'y'] out.txt. When metavar is a tuple, the help text names each value separately, as in --point X Y.
The nargs="?" option --out has three outcomes:
- If
--outis absent, the value isdefault(Nonehere). - If
--outappears with no value, the value isconst("out.txt"). - If
--out report.txtappears, the value is"report.txt".
const is only meaningful for nargs="?" and for a few actions such as store_const. Setting it elsewhere does nothing useful.
Greedy options swallow positionals
An option with nargs="*" or "+" keeps consuming every following word that does not start with a dash. This is the most common surprise with multiple values.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("--tag", nargs="*", default=[])
parser.add_argument("files", nargs="+")
print(parser.parse_args(["f.txt", "--tag", "a", "b"]))
parser.parse_args(["--tag", "a", "b", "f.txt"])The first call prints Namespace(tag=['a', 'b'], files=['f.txt']). In the second call, --tag takes a, b and f.txt. No value is left for files, so the parser exits with demo: error: the following arguments are required: files.
Two designs avoid the problem:
- Document that positionals come first, as in the working call above.
- Use
action="append"with one value per occurrence (--tag a --tag b). Users type a little more, but the parse is never ambiguous.
Defaults
When the user omits an argument, its value comes from default. If you give no default, it is None. Positionals with nargs="*" are the exception: with no default they become an empty list.
Several details matter in practice:
- String defaults go through
type. Ifdefaultis a string, argparse converts it as if the user had typed it.type=int, default="3"stores the integer3. A non-string default, such asdefault=3, is stored as is and is not converted. - Defaults on positionals only apply when the positional is optional. A positional is optional only with
nargs="?"or"*". Fornargs="?",defaultis used when the word is missing. argparse.SUPPRESSremoves the attribute. Withdefault=argparse.SUPPRESS, the attribute does not exist on the namespace unless the user supplied it. This is useful when you need to tell "not given" apart from any real value, and it works withhasattr.set_defaultsoverrides per parser.parser.set_defaults(retries=5)replaces the default declared on the argument namedretries. It can also add attributes that no argument defines, which is how the subcommands chapter stores handler functions.appendextends the default. Withaction="append", new values are added to a copy of the default list. They do not replace it.
import argparse
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument("--token", required=True, help="API token")
parser.add_argument("--retries", type=int, default="3")
parser.add_argument("--header", action="append", default=["Accept: */*"])
parser.add_argument("--timeout", type=float, default=argparse.SUPPRESS)
args = parser.parse_args(["--token", "abc", "--header", "X-Id: 7"])
print(repr(args.retries), args.header, hasattr(args, "timeout"))This prints 3 ['Accept: */*', 'X-Id: 7'] False. The retries default arrives as an integer, the appended header joins the default header, and timeout is absent from the namespace.
Required options
Positional arguments are required unless nargs is "?" or "*". Options are optional by default, because a dash prefix signals that the user may leave them out. Pass required=True to change that. In the fetch example above, running with no arguments prints a usage line and fetch: error: the following arguments are required: --token, then exits with status 2.
Some consequences of required=True:
- A default on a required option is never used, because the parser fails before it would apply. Choose one or the other.
- The usage line shows required options without square brackets, so users can see them. The help text lists them under "options" together with the others, so a mention in
helpis useful. - An option must be given either way, so
required=Trueon a flag such asstore_trueis a design smell. A flag that must always be present carries no information.
A required option is still a strange thing to ask of a user. If the command cannot work without a value, a positional argument is usually the more natural interface. Reserve required options for values that benefit from a name, such as --token, --input and --output. Those are easier to read in a script than three bare words in a fixed order.
The parser decides what happens to each argument as follows:
Interactions to watch
- Counts are checked at parse time. With
nargs=2, giving three values makes the extra word an unrecognized argument, and giving one is an error. The user sees a usage message either way. - Empty
"*"is valid. A positional withnargs="*"accepts zero values. If the program needs at least one, use"+"so the parser reports the problem rather than your code. - Two greedy positionals are ambiguous. Argparse cannot split a list of words between two
nargs="+"positionals. Give only one positional a variable length. - Defaults and
choices. The default is not checked againstchoicesunless it is a string that passes throughtype. Make sure a non-string default is itself a valid choice.
Exercise
A parser defines --include with nargs="+" and a positional target with no nargs. A user runs tool --include a.py b.py out/, and the parser reports that target is missing. Why does this happen, and what are two ways to fix the design?
Show answer
--include is greedy. It consumes a.py, b.py and out/, so nothing is left for target. One fix is to require users to put the positional first: tool out/ --include a.py b.py. The other is to change --include to action="append" with one value per use, so tool --include a.py --include b.py out/ parses unambiguously.
Exercise
What does the following print? p = argparse.ArgumentParser(); p.add_argument("--n", type=int, default="4"); p.add_argument("--xs", action="append", default=[1]); a = p.parse_args(["--xs", "2"]); print(repr(a.n), a.xs)
Show answer
It prints 4 [1, 2]. The string default "4" goes through type=int and becomes the integer 4. The append action adds 2 to a copy of the default list [1].