Use a subcommand to select a dry-run action
argparse subcommands make the selected operation visible in the command shape, instead of making a dry-run behavior depend only on a boolean flag. This example creates a dry-run subparser with one positional target. Its set_defaults() call stores a callable as action, so parsing the synthetic arguments dry-run cache produces a namespace containing the subcommand name, target, and selected action.
The action returns a preview string; it does not delete a cache or access the filesystem. The assertions verify that parsing selected dry-run, that the callable produced the expected preview, and that the output is exactly would-delete cache. This keeps parsing and dispatch close together while making the dry-run path explicitly testable.
add_subparsers() creates the command group. Passing required=True means parsing without a subcommand is an error; that option requires Python 3.7 or later. set_defaults() can attach arbitrary values to the parsed namespace, but it does not ensure that actions from several subcommands accept compatible arguments. Define and test that interface when adding commands. More generally, a dry run is only a preview: it cannot establish that a later real operation will succeed when permissions, concurrent changes, or external state have changed.
Python added argparse in 3.2. The official add_subparsers() reference documents subcommand creation, and set_defaults() documents namespace defaults.
AI assistance disclosure: This article was drafted with AI assistance and should be adapted to the application's command contract.
import argparse
def preview_delete(target):
return f"would-delete {target}"
def build_parser():
parser = argparse.ArgumentParser(prog="cachectl")
commands = parser.add_subparsers(dest="command", required=True)
dry_run = commands.add_parser("dry-run")
dry_run.add_argument("target")
dry_run.set_defaults(action=preview_delete)
return parser
arguments = build_parser().parse_args(["dry-run", "cache"])
result = arguments.action(arguments.target)
assert arguments.command == "dry-run"
assert result == "would-delete cache"
print(result)
would-delete cache
Comments
Post a Comment