Sub topic 4
Options and flags
This chapter assumes you can build a parser and read its result with parse_args, and that you have seen positional arguments. Here you add optional arguments to a parser.
What makes an argument an option
If a name passed to add_argument starts with -, argparse treats it as an option. A name without a dash is a positional argument. Options are optional by default and can appear in any order, before or after positionals.
An option that takes a value, such as --output out.txt, is usually just called an option. An option that takes no value and only switches something on, such as --dry-run, is called a flag.
import argparse
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument("url")
parser.add_argument("-o", "--output", metavar="FILE",
help="write to FILE instead of stdout")
parser.add_argument("-t", "--timeout", type=float, default=10.0,
help="seconds to wait (default: %(default)s)")
parser.add_argument("--dry-run", action="store_true",
help="show what would happen without doing it")
args = parser.parse_args(["-o", "out.txt", "--dry-run", "http://example.com"])
print(args)This prints:
Namespace(url='http://example.com', output='out.txt', timeout=10.0, dry_run=True)Short and long names
You can give one option 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 easier to read in scripts.
argparse builds the attribute name from the first long name. It removes the leading dashes and turns remaining hyphens into underscores, so --dry-run becomes args.dry_run. If you pass only a short name, the attribute uses that letter. To choose the name yourself, pass dest="name".
Writing values on the command line
All of these forms are equivalent for an option that takes a value:
| Form | Example |
|---|---|
| Separate word | `-o out.txt`, `--output out.txt` |
| Equals sign | `--output=out.txt` |
| Attached short value | `-oout.txt` |
Short flags can be combined. If -v and -q are both flags, -vq sets both. A short option that takes a value can end the group, as in -vo out.txt.
Defaults when an option is absent
If the user omits an option, its attribute is None, unless you set default. A flag created with store_true defaults to False. Test for None explicitly when 0 or an empty string is a valid value.
parser = argparse.ArgumentParser(prog="fetch")
parser.add_argument("--retries", type=int)
print(parser.parse_args([]).retries)
print(parser.parse_args(["--retries", "0"]).retries)This prints None and then 0. Writing if args.retries: would treat the second case as missing, while if args.retries is not None: handles it correctly.
Common errors
- Negative numbers. A value such as
-5looks like an option. argparse accepts it only if the parser has no option that looks like a negative number. Otherwise, write--offset=-5. - Abbreviations. By default, argparse accepts unambiguous prefixes, so
--drymatches--dry-run. A new option added later can make old abbreviations ambiguous. Passallow_abbrev=FalsetoArgumentParserto turn this off. - Wrong attribute name.
args.dry-runis a syntax error in Python. Useargs.dry_run. - Forgetting that options are optional. Your code must handle
Nonefor every option without a default.
Exercise
A parser defines parser.add_argument("-n", "--max-items", type=int). What is the attribute name on the result, and what value does it have when the user runs the program with no options?
Show answer
The attribute is args.max_items, because the leading dashes are removed and the hyphen becomes an underscore. Its value is None, since no default was given.