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=booltoparser.add_argument("--flag", type=bool):argparsepasses the raw CLI string to whatever callable is supplied totype=. Callingbool("False"),bool("0"), orbool("no")returnsTruein Python because every non-empty string is truthy—so--flag Falsesilently parses asTrue!
argparse.BooleanOptionalActionautomatically generates--flagand--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-sslin-h/--helpoutput automatically. Note: passing both--ssl --no-sslin the same command lets whichever appears last on the command line win.
- Available since Python 3.9,
- Accepting explicit
--flag true/--flag falsekey-value arguments (CI/CD & config wrappers):- If an external runner or shell wrapper requires
--flag trueor--flag=falsesyntax instead of presence flags, supply a custom converter function totype=: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)
- If an external runner or shell wrapper requires
- Short single-letter flag bundling (
-vf):- Multiple
action="store_true"short flags can be combined on the CLI as-vf(equivalent to-v -f).BooleanOptionalActionsupports short options too (parser.add_argument("-d", "--debug", action=argparse.BooleanOptionalAction)), though--no-debugonly applies to the long name.
- Multiple
- Mutually exclusive boolean groups (
add_mutually_exclusive_group()):- On Python 3.8 or when you want passing both
--enableand--disableto fail immediately with an error rather than letting the last flag win, usegroup = parser.add_mutually_exclusive_group()withaction="store_true"on--enableandaction="store_false"on--disablesharing the samedest=.
- On Python 3.8 or when you want passing both
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. |
You must log in or register to comment.
