Sub topic 5
Actions: booleans, counters and repeated options
This chapter assumes you can build a parser, add options with add_argument, and read the resulting Namespace. You should also know that an option's dest is the attribute name on that namespace. Here you will learn what the action argument does and how to pick the right one.
What an action is
An action is the rule argparse applies when it meets an option on the command line. It decides what to store in the namespace and whether the option consumes a value. If you don't pass action, you get "store": consume one value, convert it with type, and save it under dest.
Every action in this chapter is chosen with the action= keyword:
| Action | Takes a value? | What it stores |
|---|---|---|
| `store` | Yes | The converted value. A later use replaces an earlier one. |
| `store_const` | No | The fixed `const` value. |
| `store_true` / `store_false` | No | `True` / `False`. |
| `BooleanOptionalAction` | No | `True` for `--x`, `False` for `--no-x`. |
| `count` | No | How many times the option appeared. |
| `append` | Yes | A list with one item per use. |
| `append_const` | No | A list of `const` values, one per use. |
| `extend` | Yes, one or more | A flat list of every value from every use. |
| `version` | No | Nothing. Prints the version and exits. |
Booleans with store_true and store_false
A flag is an option that carries no value. Its presence is the information. store_true sets the attribute to True when the flag appears. Otherwise the attribute is False.
parser.add_argument("-n", "--dry-run", action="store_true")store_false is the mirror image. Its default is True, and the flag turns the attribute off. Name the flag for what the user types and use dest for what your code reads:
parser.add_argument("--no-cache", action="store_false", dest="cache")Your code then checks if args.cache: and never has to reason about a double negative.
A flag never accepts a value. --dry-run=yes is a usage error. Don't try to build a boolean option with type=bool. Python's bool("False") is True, because any non-empty string is truthy, so --debug False would turn debugging on.
On and off pairs with BooleanOptionalAction
Sometimes a setting has a default and users need to override it in either direction, for example a config file or environment variable may turn something on. argparse.BooleanOptionalAction (Python 3.9 and later) creates both --color and --no-color from one declaration:
parser.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)If you leave out default, the attribute is None when neither form is given. That lets you tell "the user said nothing" apart from "the user said no", which is useful when you layer command-line options over a config file.
Fixed values with store_const
store_const stores the const you declare. It is most useful when several options write to the same dest to act as named modes. The last one on the command line wins.
Counters, repeated options and the version action
The following program combines the remaining actions in one parser. It is complete and runs as shown.
import argparse
import logging
def build_parser():
parser = argparse.ArgumentParser(prog="backup")
parser.add_argument("--version", action="version", version="%(prog)s 1.2.0")
parser.add_argument("-n", "--dry-run", action="store_true",
help="show what would be copied")
parser.add_argument("-v", "--verbose", action="count", default=0,
help="increase detail (-v info, -vv debug)")
parser.add_argument("-e", "--exclude", action="append", default=[],
metavar="PATTERN",
help="skip matching paths; may be repeated")
return parser
def main(argv=None):
args = build_parser().parse_args(argv)
levels = [logging.WARNING, logging.INFO, logging.DEBUG]
logging.basicConfig(level=levels[min(args.verbose, len(levels) - 1)])
logging.info("dry run: %s", args.dry_run)
logging.debug("excluding: %s", args.exclude)
return 0
if __name__ == "__main__":
print(build_parser().parse_args(["-vv", "-n", "-e", "*.tmp", "-e", "*.log"]))
raise SystemExit(main())The print line outputs Namespace(dry_run=True, verbose=2, exclude=['*.tmp', '*.log']).
count
count adds one each time the option appears. Short flags can be bundled, so -vvv and -v -v -v both give 3. Set default=0. Without it, an absent option leaves the attribute as None, and None >= 1 raises a TypeError. The min(...) in main keeps -vvvvv from indexing past the end of the list. count is the standard way to build the -v, -vv verbosity ladder.
append
append collects one item per use, in order. Each use needs its own value: -e a -e b, not -e a b. With default=[], argparse copies the list before appending, so the default object is not modified between parses.
Be careful with a non-empty default. User values are added after it, not in place of it:
parser.add_argument("-e", "--exclude", action="append", default=[".git"])
# -e build -> ['.git', 'build']The default stays in the list even when the user wanted to replace it. If users need to replace the default, use default=None and fill it in after parsing:
args = parser.parse_args(argv)
if args.exclude is None:
args.exclude = [".git"]version
The version action prints its string and exits with status 0 as soon as it is seen. It stores nothing, so version never appears in the namespace. %(prog)s expands to the program name. A common source is the package metadata, such as importlib.metadata.version("backup"), which keeps the number in one place.
Other actions in one parser
store_const, append_const and extend fit in one short parser. It also shows which defaults win when several options share a dest.
import argparse
parser = argparse.ArgumentParser(prog="build")
parser.add_argument("--fast", action="store_const", const="fast",
dest="mode", default="normal")
parser.add_argument("--thorough", action="store_const", const="thorough",
dest="mode")
parser.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
parser.add_argument("--no-cache", action="store_false", dest="cache")
parser.add_argument("--with-docs", action="append_const", const="docs", dest="steps")
parser.add_argument("--with-tests", action="append_const", const="tests", dest="steps")
parser.add_argument("--tag", action="extend", nargs="+", default=[])
print(parser.parse_args([]))
print(parser.parse_args([
"--thorough", "--no-color", "--no-cache",
"--with-tests", "--with-docs", "--tag", "a", "b", "--tag", "c",
]))The output is:
Namespace(mode='normal', color=True, cache=True, steps=None, tag=[])
Namespace(mode='thorough', color=False, cache=False, steps=['tests', 'docs'], tag=['a', 'b', 'c'])Three details are worth noting:
--fastand--thoroughsharedest="mode". The first option declared supplies the default, so putdefault="normal"on the first one.append_constbuilds a list of markers, one per option present, in command-line order. It has no value to parse, so it suits switches like--with-docs.extend(Python 3.8 and later) flattens, so--tag a b --tag cgives['a', 'b', 'c'].appendwithnargs="+"would give[['a', 'b'], ['c']].
Common errors
- Forgetting
default=0oncount. Code that compares the counter fails when the option is absent. - Using
type=bool. Usestore_trueorBooleanOptionalActioninstead. If you need a value such asyesorno, write a customtypefunction. - Expecting
appendto replace its default. It extends the default. - Passing a
typeto a flag.store_true,countand the_constactions rejecttype,choicesandnargs.argparseraisesTypeErrorwhile you build the parser, not when it parses user input. - Naming the attribute from the wrong spelling.
--dry-runbecomesargs.dry_run, because dashes turn into underscores. Withstore_falseand--no-cache, setdestexplicitly, or you will readargs.no_cache.
Exercises
Exercise
A parser has -v with action="count" and default=0. What is args.verbose for the arguments ["-vv", "-v"], and what would it be for [] if default=0 were removed?
Show answer
It is 3, because the counts from -vv and -v add up. For [] without the default, it is None, because count has no initial value of its own. That is why count options should set default=0.
Exercise
You declare --tag with action="append" and nargs="+". What does --tag a b --tag c produce, and which action gives ['a', 'b', 'c'] instead?
Show answer
It produces [['a', 'b'], ['c']], a list of lists, because append adds each use as one item. action="extend" with nargs="+" flattens the values into ['a', 'b', 'c'].
Exercise
Which action would you use for a setting that is on by default, where users must be able to say both --progress and --no-progress? What is the attribute's value if you set no default and the user gives neither?
Show answer
Use argparse.BooleanOptionalAction. Without a default, the attribute is None when neither form is given. With default=True, the attribute is True when neither form is given.