Sub topic 4
Options and Flags
This chapter assumes you can build an ArgumentParser and call parse_args, and that you have seen a positional argument. It covers how optional arguments are declared and parsed, how their names turn into attributes, and the edge cases that cause confusing errors.
Options versus flags
An argparse argument is optional when its name starts with a dash. Two terms are used loosely, so this chapter fixes them:
- An option takes a value, such as
--output page.html. - A flag takes no value. Its presence switches something on, such as
--verbose.
Both are declared with add_argument. The difference comes from the action. The default action is store, which consumes one value. The store_true action consumes none. Actions get their own chapter, so here store_true is only the standard way to make a flag.
import argparse
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument("url")
parser.add_argument("-o", "--output", help="file to write to")
parser.add_argument("-t", "--timeout", type=float, default=10.0,
help="seconds to wait (default: %(default)s)")
parser.add_argument("--follow-redirects", action="store_true",
help="follow HTTP redirects")
args = parser.parse_args(["https://example.com", "-o", "page.html", "--follow-redirects"])
print(args.url)
print(args.output)
print(args.timeout)
print(args.follow_redirects)This prints the URL, page.html, 10.0 and True. Three things are worth noting:
--outputwas given, so it holds the string you passed.--timeoutwas omitted, so it holds its default.--follow-redirectsisTruebecause the flag appeared. Without it the value would beFalse.
Short and long names
You can give one argument several names. By convention a short name is a single dash and one letter (-o). A long name is two dashes and a word (--output). Short names are quick to type. Long names are readable in scripts and documentation. Offer a long name for every option, and add a short name only for options people will type often.
Short names must be one character. Long names must not be. argparse decides which is which by the number of leading dashes, so -output is accepted but is treated as a short option that happens to have a long name. Avoid it.
From name to attribute: dest
The parsed value is stored on the result under a name called dest. If you don't set it, argparse derives it with these rules:
- Use the first long option name if there is one. Otherwise use the first short name.
- Remove the leading dashes.
- Replace remaining hyphens with underscores.
| Declaration | Attribute |
|---|---|
| `"-o", "--output"` | `args.output` |
| `"--follow-redirects"` | `args.follow_redirects` |
| `"-n"` | `args.n` |
| `"-d", "--dest-dir", dest="target"` | `args.target` |
The hyphen-to-underscore rule exists because args.follow-redirects is not valid Python. Set dest explicitly when the derived name is poor or when two options should write to the same attribute.
Ways to supply a value
A single option can be written in several equivalent forms.
import argparse
parser = argparse.ArgumentParser(prog="demo")
parser.add_argument("-o", "--output")
parser.add_argument("-v", "--verbose", action="store_true")
parser.add_argument("-q", "--quiet", action="store_true")
forms = [
["-o", "a.txt"],
["-oa.txt"],
["--output", "a.txt"],
["--output=a.txt"],
["--out", "a.txt"],
]
for form in forms:
print(form, "->", parser.parse_args(form).output)
combined = parser.parse_args(["-vqo", "a.txt"])
print(combined.verbose, combined.quiet, combined.output)All five forms give a.txt. The last line prints True True a.txt. Short flags can be combined into one token (-vq). The final letter in a cluster may take a value, so -vqo a.txt works.
The form --out is an unambiguous prefix of --output, and argparse accepts it. That is convenient interactively but risky in a tool other programs call. If you later add --outfile, then --out becomes ambiguous and old scripts break. Pass allow_abbrev=False to ArgumentParser to disable prefix matching.
How argparse classifies each token
Before it stores anything, the parser walks the argument list and decides what each token is. Knowing this explains most of the surprising errors.
Three consequences follow.
Values that start with a dash
A value like -5 works as an option's value, because argparse recognizes negative numbers. A value like -x does not, because it looks like an option.
import argparse
parser = argparse.ArgumentParser(prog="shift", exit_on_error=False)
parser.add_argument("--offset", type=int)
parser.add_argument("--pattern")
print(parser.parse_args(["--offset", "-5"]).offset)
print(parser.parse_args(["--pattern=-x"]).pattern)
try:
parser.parse_args(["--pattern", "-x"])
except argparse.ArgumentError as err:
print("error:", err)The first call prints -5. The second prints -x, because the = form binds the value to the option unambiguously. The third raises an error saying the option expects one argument. When a value may begin with a dash, tell users to write --option=value.
The double-dash separator
A bare -- ends option parsing. Everything after it is treated as positional, even if it starts with a dash. This is how tools such as grep -- -v file search for a literal -v. It only helps positional arguments. It does not rescue an option value.
Options and positionals can be interleaved
Options may appear before, between, or after positionals. fetch URL -o x and fetch -o x URL are the same. Do not rely on order unless you have a reason.
Controlling the help and usage display
Two parameters affect how an option appears in --help:
metavarreplaces the placeholder shown for the value. Without it, argparse uses the uppercaseddest, so--dest-dirshowsDEST_DIR.helpis the description. It may use%(default)s,%(dest)sand similar placeholders.
import argparse
parser = argparse.ArgumentParser(prog="backup")
parser.add_argument("-d", "--dest-dir", dest="target", metavar="DIR",
required=True, help="where to write the backup")
parser.print_usage()This prints usage: backup [-h] -d DIR. The -d DIR appears without brackets because the option is required.
Required options and defaults
Options are optional by default, which is why they are called options. If you omit one, its attribute is the default, and None when you gave no default. Setting required=True makes the parser exit with an error when it is missing.
Use required=True sparingly. A value that must always be supplied is usually better as a positional argument, because the usage line then reads naturally and the user does not type a name for it. Required options make sense when there are several mandatory values of the same kind and names make the call clearer, as in --src and --dst.
A few details about defaults:
- If the default is a string, argparse runs it through
typeas if the user had typed it. A default of"10"withtype=intbecomes10. Non-string defaults are used as they are. - A default of
Noneis a useful signal for "the user said nothing". You can then apply a fallback, such as an environment variable, inmainrather than in the parser. - With
store_true, the default isFalse. Withstore_false, it isTrue.
Common mistakes
- Forgetting that dashes become underscores.
--dry-runis read asargs.dry_run. - Using
type=bool. Any non-empty string, including"False", converts toTrue. Usestore_trueor a custom converter. - Giving a flag a default and
store_truewithout thinking.store_truewithdefault=Truecan never be turned off. - Letting two options share a
destby accident. The later default overwrites the earlier one. - Accepting prefix abbreviations in a tool that scripts rely on. See the warning above.
Exercise
A parser declares parser.add_argument("-l", "--log-level", default="info"). (a) What attribute holds the value? (b) A user runs the tool with --log-level -x. Why does this fail, and how should they write it instead?
Show answer
(a) The attribute is args.log_level. argparse takes the first long name, strips the dashes and replaces the hyphen with an underscore. (b) The token -x starts with a dash and does not look like a negative number, so argparse treats it as an option and reports that --log-level expected one argument. The user should write --log-level=-x, which binds the value to the option explicitly.
Exercise
You write parser.add_argument("--debug", type=bool) and the user runs tool --debug False. What value does args.debug hold, and what declaration should you use?
Show answer
It holds True. The bool constructor returns True for any non-empty string, and "False" is non-empty. Declare it as parser.add_argument("--debug", action="store_true"), so the flag takes no value and its presence means True.