Python › Command-Line Interfaces (argparse)

How do you implement boolean flags using action='store_true' and action='store_false'?

Intermediate

Answer

'action="store_true"' makes a flag default to False and become True if PRESENT on the command line (no value needed after it); 'action="store_false"' is the inverse, defaulting to True and becoming False if present — both avoid needing the user to type an explicit 'True'/'False' string.
parser.add_argument("--verbose", action="store_true", help="Enable verbose output")
parser.add_argument("--no-color", action="store_false", dest="use_color", help="Disable colored output")
args = parser.parse_args(["--verbose"])
print(args.verbose)    # True
print(args.use_color)  # True (default, since --no-color wasn't passed)
Real-world example Implementing a simple --verbose or --debug toggle flag that doesn't require a value, just its presence or absence.

Common follow-ups: How does the 'dest' parameter let a flag named '--no-color' set an attribute actually named 'use_color'?