Sub topic 7
Multiple values, defaults and required options
This chapter assumes you can already declare positional arguments and options with add_argument. It covers how many values an argument accepts, what it holds when the user omits it, and how to make an option mandatory.
Controlling how many values an argument takes
The nargs parameter sets how many command-line words one argument consumes. Without it, an argument takes exactly one value and stores a single string.
| `nargs` | Meaning | Result type |
|---|---|---|
| omitted | exactly one value | single value |
| `3` (any integer) | exactly that many values | list |
| `"?"` | zero or one value | single value, or the default |
| `"*"` | zero or more values | list |
| `"+"` | one or more values | list |
An integer, "*" or "+" always produces a list, even when only one value is given. With type=int, each item in the list is converted separately.
Defaults and required options
An option that the user omits gets its default, which is None unless you set another value. If the default is a string, argparse runs it through type as if the user had typed it. A default that is not a string is used as it is.
Options are optional by default. Add required=True to make argparse reject a command line that leaves the option out. Positional arguments are required unless nargs is "?" or "*".
import argparse
def build_parser():
parser = argparse.ArgumentParser(prog="resize")
parser.add_argument("files", nargs="+", help="input image files")
parser.add_argument("dest", nargs="?", default=".",
help="output directory (default: %(default)s)")
parser.add_argument("--size", nargs=2, type=int, metavar=("W", "H"),
default=[800, 600], help="target width and height")
parser.add_argument("--tag", nargs="*", default=[],
help="labels to attach")
parser.add_argument("--format", default="png")
parser.add_argument("--owner", required=True)
return parser
args = build_parser().parse_args(
["a.jpg", "--owner", "ada", "--size", "640", "480"]
)
print(args.files, args.dest, args.size, args.tag, args.format, args.owner)This prints ['a.jpg'] . [640, 480] [] png ada. Four of the six values come from defaults or conversion:
destwas omitted, so it takes the default..tagwas omitted, so it is the empty list.sizewas converted to integers.formatwas omitted, so it ispng.
If you leave out --owner, argparse prints error: the following arguments are required: --owner to stderr and exits with status 2.
Gotchas
An option with nargs="*" or "+" keeps consuming words until it reaches another option. In resize --tag red blue a.jpg, the filename a.jpg becomes a tag, and argparse then complains that files is missing. There are two fixes:
- Put the positional arguments before the option.
- Put
--between them, as inresize --tag red blue -- a.jpg.
Be careful with required=True. A "required option" is a contradiction in terms for many users, who expect options to be optional. If a value must always be supplied, consider making it a positional argument. Use required=True when the name makes the command line easier to read.
Exercise
A tool defines parser.add_argument("paths", nargs="*") and parser.add_argument("--limit", type=int, default="5"). When the user runs it with no arguments, what are args.paths and args.limit?
Show answer
args.paths is [], because nargs="*" allows zero values and produces an empty list. args.limit is 5 as an integer, because a string default is passed through type=int.
Exercise
Why does tool --tag red blue a.jpg fail when --tag uses nargs="*" and files is a required positional argument? Give one fix.
Show answer
--tag consumes every word up to the next option, so a.jpg is taken as a tag and files receives nothing. Put files first, or write tool --tag red blue -- a.jpg.