Programs That Take Arguments · practice
Add One Validated Option
Positional paths answer which files to use. The remaining interface decision is optional: keep only items whose quantity reaches a caller’s threshold.
Validate before conversion starts
argparse can call a conversion
def non_negative_int(text):
try:
value = int(text)
except ValueError:
raise argparse.ArgumentTypeError("must be a non-negative integer")
if value < 0:
raise argparse.ArgumentTypeError("must be a non-negative integer")
return value
This failure belongs to the interface grammar, not to catalog data. Argparse uses the ArgumentTypeError message as its explanation, shows usage on stderr, and finishes with status 2 before the input file is opened. It also catches a plain ArgumentTypeError when you want the caller to see your specific rule.
Add the option to build_parser:
parser.add_argument(
"--minimum-quantity",
type=non_negative_int,
default=0,
metavar="COUNT",
help="keep items whose quantity is at least COUNT (default: 0)",
)
The default preserves the earlier converter: leaving the option out keeps every valid item.
Filter values, not files
Add select_items(items, minimum_quantity). Visit the already normalized item item["quantity"] >= minimum_quantity, and return the new
Change convert_catalog to accept minimum_quantity=0, select after read_catalog_csv, and write the selected list through the same validated JSON writer. Finally, pass args.minimum_quantity from main.
Three things are worth checking by hand. Run with --minimum-quantity 0 and confirm you get every item, so the default really is harmless. Run with a threshold that excludes everything and confirm you get an empty item list rather than a crash. Then put some text in the output file, run with --minimum-quantity -1, and confirm your text is still there: argparse should have rejected the command before anything opened that file.
Why raise argparse.ArgumentTypeError rather than ValueError in the option converter?
Why does --minimum-quantity default to 0?
Task
Add the one declared catalog option.
Define
non_negative_int(text)so non-integers and negative integers raiseargparse.ArgumentTypeError("must be a non-negative integer").Add
--minimum-quantity COUNTwith that type, default0, and the declared help text.Define
select_items(items, minimum_quantity)and preserve input order and duplicates while keeping quantities greater than or equal to the threshold.Give
convert_cataloga defaultedminimum_quantity, select the normalized items, and write only that result. Forward the parsed option from
main.
Do not move CSV parsing, JSON writing, or schema validation into the parser.