Use argparse BooleanOptionalAction for a local switch

A local on/off setting is often clearer when users can state either choice directly. argparse.BooleanOptionalAction creates the positive and negative long options from one declaration. Adding --cache with this action also accepts --no-cache; the first stores True and the second stores False.

The example sets default=True, which represents the application's chosen behavior when neither option appears. It then parses three fixed argument lists. An empty list keeps the default, --no-cache disables caching, and --cache explicitly enables it. The assertion checks that the resulting values are [True, False, True], and print(*values) produces the exact output True False True. Passing lists directly to parse_args() keeps the sample independent of the program that launches it.

This action is appropriate for a boolean setting, not a value-taking option. Avoid type=bool for text such as --cache False: Python considers non-empty strings truthy, so that spelling does not express the expected false value. BooleanOptionalAction also does not resolve conflicts between repeated flags; normal argument parsing processes them in order, so an interface should document whether repeated contradictory switches are allowed. The example makes no claim about cache implementation, persistence, or performance; it only parses a local switch.

BooleanOptionalAction was added in Python 3.9, so use Python 3.9 or newer for this exact declaration. AI assistance disclosure: this article was drafted with AI assistance.

See the official argparse documentation.

import argparse

parser = argparse.ArgumentParser(add_help=False)
parser.add_argument(
    "--cache",
    action=argparse.BooleanOptionalAction,
    default=True,
)

values = [
    parser.parse_args(arguments).cache
    for arguments in ([], ["--no-cache"], ["--cache"])
]

assert values == [True, False, True]
print(*values)
True False True

Comments

Popular posts from this blog

Compare Two Text Files in Python Without Modifying Them

Seven CSV Quality Checks to Run Before Importing Data

Explain why SQLite transactions cannot make an HTTP call atomic