How do you correctly parse boolean command-line flags using Python argparse? | A1Lab@MZeeshanM to PythonEnglish • 2 days ago

How do you correctly parse boolean command-line flags using Python argparse?

message-square
0

Use action="store_true" (default False, becomes True when --flag is passed) or action="store_false" (default True, becomes False when --no-flag is passed) for standard presence/absence switches—and action=argparse.BooleanOptionalAction (Python 3.9+) whenever you want automatic paired --flag / --no-flag support—never type=bool, because Python’s bool("False") evaluates to True since any non-empty string is truthy.

Basic Example

import argparse

parser = argparse.ArgumentParser(description="Configure job execution flags.")

# 1. Standard flag (defaults to False; passing `--verbose` sets args.verbose = True):
parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose logging")

# 2. Inverted flag (defaults to True; passing `--no-cache` sets args.cache = False):
parser.add_argument("--no-cache", dest="cache", action="store_false", help="Disable local cache")

# 3. Recommended for paired `--feature` / `--no-feature` switches (Python 3.9+):
parser.add_argument(
    "--dry-run",
    action=argparse.BooleanOptionalAction,
    default=False,
    help="Simulate changes without writing to disk",
)

args = parser.parse_args(["--verbose", "--no-cache", "--dry-run"])
print(args)
# Output: Namespace(verbose=True, cache=False, dry_run=True)

args_negated = parser.parse_args(["--no-dry-run"])
print(args_negated)
# Output: Namespace(verbose=False, cache=True, dry_run=False)

Key Details & Edge Cases

  • Never pass type=bool to parser.add_argument("--flag", type=bool):
    • argparse passes the raw CLI string to whatever callable is supplied to type=. Calling bool("False"), bool("0"), or bool("no") returns True in Python because every non-empty string is truthy—so --flag False silently parses as True!
  • argparse.BooleanOptionalAction automatically generates --flag and --no-flag:
    • Available since Python 3.9, parser.add_argument("--ssl", action=argparse.BooleanOptionalAction, default=True) accepts both --ssl (True) and --no-ssl (False), and displays --ssl, --no-ssl in -h / --help output automatically. Note: passing both --ssl --no-ssl in the same command lets whichever appears last on the command line win.
  • Accepting explicit --flag true / --flag false key-value arguments (CI/CD & config wrappers):
    • If an external runner or shell wrapper requires --flag true or --flag=false syntax instead of presence flags, supply a custom converter function to type=:
      def str_to_bool(val: str) -> bool:
          normalized = val.strip().lower()
          if normalized in {"true", "1", "yes", "y", "on"}:
              return True
          if normalized in {"false", "0", "no", "n", "off"}:
              return False
          raise argparse.ArgumentTypeError(f"Invalid boolean value: '{val}'")
      
      parser.add_argument("--debug", type=str_to_bool, default=False)
      
  • Short single-letter flag bundling (-vf):
    • Multiple action="store_true" short flags can be combined on the CLI as -vf (equivalent to -v -f). BooleanOptionalAction supports short options too (parser.add_argument("-d", "--debug", action=argparse.BooleanOptionalAction)), though --no-debug only applies to the long name.
  • Mutually exclusive boolean groups (add_mutually_exclusive_group()):
    • On Python 3.8 or when you want passing both --enable and --disable to fail immediately with an error rather than letting the last flag win, use group = parser.add_mutually_exclusive_group() with action="store_true" on --enable and action="store_false" on --disable sharing the same dest=.

Comparison of Boolean Flag Patterns in Python argparse

Pattern CLI Syntax Accepted Default Value Python Version Best Used When
action="store_true" (Recommended for opt-in flags) --verbose or -v (presence = True) False All Python 3 Standard opt-in CLI switches (--verbose, --force, --quiet).
action="store_false" (Recommended for opt-out flags) --no-cache (presence = False) True All Python 3 Features enabled by default that users occasionally disable (--no-color, --no-verify).
action=argparse.BooleanOptionalAction (Recommended for dual switches) --dry-run (True) or --no-dry-run (False) Configurable (default=True/False/None) Python 3.9+ Overriding config-file defaults in either direction (--ssl vs. --no-ssl).
type=str_to_bool custom function --debug true, --debug=0, --debug false Configurable (default=False) All Python 3 Integrating with CI/CD pipelines, Docker entrypoints, or wrappers that pass --flag=true/false.
type=bool (Broken anti-pattern) --flag False $\rightarrow$ evaluates to True! — Never use Never use—bool("False") is True in Python.