Batu Lab NotesPractical developer guides

Use argparse choices for a report format

By Batu ยท English technical notes

Also published in our Blogger archive.

A report command should reject formats it cannot implement rather than carrying an arbitrary string deeper into its code. This parser adds --format with choices=("text", "json"). When the synthetic input supplies --format json, parse_args() stores the selected string in args.format; the two assertions verify both the exact selected value and its membership in the supported set.

choices validates the parsed value, but it does not generate a report, serialize JSON, or guarantee that a future formatter understands every selected value. The restriction is case-sensitive here: JSON is not one of the listed choices. If aliases or case-insensitive input are desirable, normalize deliberately before or during parsing, then document the resulting canonical values. Keep the choice collection close to the code that dispatches formats so supported values do not drift from implementation.

This uses only the standard-library argparse module, available since Python 3.2. The official argparse reference documents choices as the allowable values for an argument and explains that invalid command-line inputs produce a parser error.

AI assistance disclosure: this article was drafted with AI assistance and should be checked in its target CLI context.

import argparse

formats = ("text", "json")
parser = argparse.ArgumentParser(prog="report")
parser.add_argument("--format", choices=formats, required=True)

args = parser.parse_args(["--format", "json"])
assert args.format == "json"
assert args.format in formats

print(f"format={args.format}")
format=json