Sub topic 5
Actions: booleans, counters and repeated options
This chapter assumes you can already declare a positional argument and an option with add_argument. It covers the action parameter, which controls what argparse does with a value once it finds the option on the command line.
What an action does
When argparse matches an option, it hands the value to an action. The default action is store, which saves the value (converted by type) under the option's destination name. Other actions change that behavior. Some take no value at all. Others collect values.
| Action | Value on the command line | Result stored |
|---|---|---|
| `store` | one value | the value |
| `store_true` | none | `True` (default `False`) |
| `store_false` | none | `False` (default `True`) |
| `store_const` | none | the `const` you set |
| `count` | none, repeatable | number of occurrences |
| `append` | one value, repeatable | list of values |
| `append_const` | none, repeatable | list of `const` values |
| `version` | none | prints the version and exits |
| `BooleanOptionalAction` | none | `True` or `False` (adds a `--no-` form) |
A worked example
import argparse
parser = argparse.ArgumentParser(prog="backup")
parser.add_argument("-v", "--verbose", action="count", default=0,
help="increase detail (repeat for more)")
parser.add_argument("-x", "--exclude", action="append", default=[],
metavar="PATTERN", help="skip matching files (repeatable)")
parser.add_argument("--dry-run", action="store_true",
help="show what would happen")
parser.add_argument("--color", action=argparse.BooleanOptionalAction,
default=True, help="colored output")
parser.add_argument("--version", action="version", version="%(prog)s 1.2.0")
args = parser.parse_args(["-vv", "-x", "*.tmp", "-x", "*.log",
"--dry-run", "--no-color"])
print(args.verbose, args.exclude, args.dry_run, args.color)Running it prints:
2 ['*.tmp', '*.log'] True FalseHere is what each option does:
-vvis two occurrences of-v, socountstores2. Short flags can be bundled, so-vvvgives3.- Each
-xadds one item to the list. The same option can appear as many times as the user likes. --dry-runis a plain flag. Its destination isdry_run, because argparse turns dashes into underscores.--coloraccepts both--colorand--no-color. It needs Python 3.9 or later.--versionprintsbackup 1.2.0and exits with status 0 before any other code runs.
Common mistakes
Always give count a default=0. Without it the value is None when the option is absent, and args.verbose >= 1 raises a TypeError.
With append, a non-empty default is not replaced. User values are added after it. If you set default=["*.pyc"] and the user passes -x "*.log", the result is ['*.pyc', '*.log']. Use default=[] or leave the default out. Without a default, the value is None when the option is absent. Then you must handle None yourself.
Counters pair well with logging. A common mapping is 0 for warnings, 1 for info and 2 or more for debug:
import logging
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(args.verbose, len(levels) - 1)])The min call keeps -vvvvv from indexing past the end of the list.
Exercise
You declare parser.add_argument("-i", "--include", action="append", default=["src"]) and run the program with -i docs -i tests. What is args.include, and how would you change the declaration so that only the user's values are kept?
Show answer
It is ['src', 'docs', 'tests'], because append adds to the default list. Change the default to [] (or omit it and treat None as empty) and check for the empty case in your code. Then the result is ['docs', 'tests']. If you want src only when the user gives nothing, test for an empty list after parsing and then set it to ["src"].