Flags and actions

argparse · Essentials · 9 min

Flags like --verbose and repeatable options like --include are in almost every CLI.

action= tells argparse what to do when it sees an option. The default, store, saves the following value. Others:

  • store_true / store_false: a flag with no value; sets True (or False). Default is the opposite.
  • count: counts occurrences, so -vvv gives 3. Set default=0, otherwise the default is None.
  • append: repeatable option collecting values into a list: --include a --include b gives ['a', 'b'].
  • extend: like append but each occurrence can take several values (with nargs), flattened into one list.
  • store_const / append_const: store a fixed const value.
  • version: prints version= text and exits: add_argument("--version", action="version", version="%(prog)s 1.2").
  • argparse.BooleanOptionalAction: creates a --color / --no-color pair in one call.

One gotcha with append and a list default: the values are appended to the default list, so default=["x"] plus --include a gives ['x', 'a'], not ['a']. Use default=None and fill in the fallback after parsing.

Example

import argparse

p = argparse.ArgumentParser(prog="tool")
p.add_argument("-v", "--verbose", action="count", default=0)
p.add_argument("--dry-run", action="store_true")
p.add_argument("-I", "--include", action="append")
p.add_argument("--color", action=argparse.BooleanOptionalAction, default=True)
p.add_argument("--version", action="version", version="%(prog)s 1.2")

a = p.parse_args(["-vvv", "-I", "src", "--include", "lib", "--no-color"])
print(a.verbose, a.dry_run, a.include, a.color)   # 3 False ['src', 'lib'] False
print(p.parse_args([]))
# Namespace(verbose=0, dry_run=False, include=None, color=True)
try:
    p.parse_args(["--version"])                   # tool 1.2
except SystemExit:
    pass

Remember

  • store_true for on/off flags, count for -vvv, append for repeatable options
  • BooleanOptionalAction gives --x and --no-x
  • action='version' prints and exits

Watch out for

  • Giving an append option a non-empty list default; user values are added to it rather than replacing it.

Check yourself

  1. add_argument('-v', action='count') with no default. What is args.v when -v is absent?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: docs.python.org/3/library/argparse.html#action